hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 12, "code_window": [ "\n", " compares.push(await page.compareScreenshot('should open custom action sheet select'));\n", "\n", " await actionSheet.callMethod('dismiss');\n", "\n", " for (const compare of compares) {\n", " expect(compare).toMatchScreenshot();\n", " }\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(ionDismiss).toHaveReceivedEvent();\n", "\n" ], "file_path": "core/src/components/select/test/basic/e2e.ts", "type": "add", "edit_start_line_idx": 86 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>List - Spec</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/core.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-list lines="none"> <ion-item> <ion-label> Single-line item </ion-label> <ion-icon name="square" slot="end"></ion-icon> </ion-item> <ion-item> <ion-label> Single-line item longer text </ion-label> </ion-item> <ion-item> <ion-icon color="tertiary" slot="start" name="bluetooth"></ion-icon> <ion-label> Single-line item </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <ion-item> <ion-avatar slot="start"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> Single-line item </ion-label> </ion-item> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label> Single-line item </ion-label> </ion-item> <ion-item> <ion-avatar slot="start"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> One-line item </ion-label> <ion-checkbox slot="end"></ion-checkbox> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-radio slot="end"></ion-radio> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-toggle slot="end"></ion-toggle> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-badge slot="end">99</ion-badge> </ion-item> <ion-item> <ion-checkbox slot="start"></ion-checkbox> <ion-label> One-line item </ion-label> </ion-item> <ion-item> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-note slot="end">meta</ion-note> </ion-item> <!-- TODO <ion-item> <ion-label> <span>Overline</span> Two-line item </ion-label> </ion-item> --> <ion-item> <ion-icon name="bluetooth" slot="start"></ion-icon> <ion-label> Two-line item <p>Secondary text</p> </ion-label> </ion-item> <ion-item> <ion-avatar slot="start"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-icon name="square" slot="end"></ion-icon> </ion-item> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-icon name="square" slot="end"></ion-icon> </ion-item> <ion-item> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> <ion-note slot="end">meta</ion-note> </ion-item> <!-- TODO <ion-item> <ion-label> <span>Overline</span> Three-line item </ion-label> </ion-item> --> <ion-item> <ion-icon slot="start" name="bluetooth"></ion-icon> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> <ion-item> <ion-avatar slot="start"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> </ion-list> <!-- Similar to the first list but flipped slots --> <ion-list lines="none"> <ion-item> <ion-avatar slot="end"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> Single-line item </ion-label> </ion-item> <ion-item> <ion-thumbnail slot="end"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label> Single-line item </ion-label> </ion-item> <ion-item> <ion-avatar slot="end"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> One-line item </ion-label> <ion-checkbox slot="start"></ion-checkbox> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-radio slot="start"></ion-radio> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-toggle slot="start"></ion-toggle> </ion-item> <ion-item> <ion-label> One-line item </ion-label> <ion-badge slot="start">99</ion-badge> </ion-item> <ion-item> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-note slot="start">meta</ion-note> </ion-item> <ion-item> <ion-icon name="bluetooth" slot="end"></ion-icon> <ion-label> Two-line item <p>Secondary text</p> </ion-label> </ion-item> <ion-item> <ion-avatar slot="end"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-icon name="square" slot="start"></ion-icon> </ion-item> <ion-item> <ion-thumbnail slot="end"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label> Two-line item <p>Secondary text</p> </ion-label> <ion-icon name="square" slot="start"></ion-icon> </ion-item> <ion-item> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> <ion-note slot="start">meta</ion-note> </ion-item> <ion-item> <ion-icon slot="end" name="bluetooth"></ion-icon> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> <ion-item> <ion-avatar slot="end"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> <ion-item> <ion-thumbnail slot="end"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label class="ion-text-wrap"> Three-line item <p>Secondary line text Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </ion-label> </ion-item> </ion-list> <style> body { margin: 0; } body, ion-list { background: #e5e5e5 !important; } ion-item { margin-bottom: 12px; } </style> </body> </html>
core/src/components/list/test/spec/index.html
0
https://github.com/ionic-team/ionic-framework/commit/b835b7c0c7840f41c54f96743cc0a779ff474ab6
[ 0.00017694444977678359, 0.00017140773707069457, 0.00016581537784077227, 0.00017156188550870866, 0.0000024884020604076795 ]
{ "id": 12, "code_window": [ "\n", " compares.push(await page.compareScreenshot('should open custom action sheet select'));\n", "\n", " await actionSheet.callMethod('dismiss');\n", "\n", " for (const compare of compares) {\n", " expect(compare).toMatchScreenshot();\n", " }\n", "});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(ionDismiss).toHaveReceivedEvent();\n", "\n" ], "file_path": "core/src/components/select/test/basic/e2e.ts", "type": "add", "edit_start_line_idx": 86 }
describe('Lifecycle', () => { it('should fire lifecycle events when navigating to and from a page', () => { cy.visit('http://localhost:8080'); cy.get('#lifecycle').click(); testLifecycle('lifecycle', { ionViewWillEnter: 1, ionViewDidEnter: 1, ionViewWillLeave: 0, ionViewDidLeave: 0, onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 0, onIonViewDidLeave: 0 }); cy.get('#lifecycle-navigation').click(); testLifecycle('lifecycle', { ionViewWillEnter: 1, ionViewDidEnter: 1, ionViewWillLeave: 1, ionViewDidLeave: 1, onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 1, onIonViewDidLeave: 1 }); cy.ionBackClick('navigation'); testLifecycle('lifecycle', { ionViewWillEnter: 2, ionViewDidEnter: 2, ionViewWillLeave: 1, ionViewDidLeave: 1, onIonViewWillEnter: 2, onIonViewDidEnter: 2, onIonViewWillLeave: 1, onIonViewDidLeave: 1 }); }); it('should fire lifecycle events when landed on directly', () => { cy.visit('http://localhost:8080/lifecycle'); testLifecycle('lifecycle', { ionViewWillEnter: 1, ionViewDidEnter: 1, ionViewWillLeave: 0, ionViewDidLeave: 0, onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 0, onIonViewDidLeave: 0 }); }); it('should fire lifecycle events when navigating to and from a page - setup', () => { cy.visit('http://localhost:8080'); cy.get('#lifecycle-setup').click(); testLifecycle('lifecycle-setup', { onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 0, onIonViewDidLeave: 0 }); cy.get('#lifecycle-navigation').click(); testLifecycle('lifecycle-setup', { onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 1, onIonViewDidLeave: 1 }); cy.ionBackClick('navigation'); testLifecycle('lifecycle-setup', { onIonViewWillEnter: 2, onIonViewDidEnter: 2, onIonViewWillLeave: 1, onIonViewDidLeave: 1 }); }); it('should fire lifecycle events when landed on directly - setup', () => { cy.visit('http://localhost:8080/lifecycle-setup'); testLifecycle('lifecycle-setup', { onIonViewWillEnter: 1, onIonViewDidEnter: 1, onIonViewWillLeave: 0, onIonViewDidLeave: 0 }); }); }) const testLifecycle = (selector, expected = {}) => { if (expected.ionViewWillEnter) { cy.get(`[data-pageid=${selector}] #willEnter`).should('have.text', expected.ionViewWillEnter); } if (expected.ionViewDidEnter) { cy.get(`[data-pageid=${selector}] #didEnter`).should('have.text', expected.ionViewDidEnter); } if (expected.ionViewWillLeave) { cy.get(`[data-pageid=${selector}] #willLeave`).should('have.text', expected.ionViewWillLeave); } if (expected.ionViewDidLeave) { cy.get(`[data-pageid=${selector}] #didLeave`).should('have.text', expected.ionViewDidLeave); } cy.get(`[data-pageid=${selector}] #onWillEnter`).should('have.text', expected.onIonViewWillEnter); cy.get(`[data-pageid=${selector}] #onDidEnter`).should('have.text', expected.onIonViewDidEnter); cy.get(`[data-pageid=${selector}] #onWillLeave`).should('have.text', expected.onIonViewWillLeave); cy.get(`[data-pageid=${selector}] #onDidLeave`).should('have.text', expected.onIonViewDidLeave); }
packages/vue/test-app/tests/e2e/specs/lifecycle.js
0
https://github.com/ionic-team/ionic-framework/commit/b835b7c0c7840f41c54f96743cc0a779ff474ab6
[ 0.00017962112906388938, 0.0001757925347192213, 0.0001714359677862376, 0.00017595291137695312, 0.000001977526608243352 ]
{ "id": 0, "code_window": [ " {...this.selectProps}\n", " {...subjectSelectProps}\n", " name=\"filter-column\"\n", " >\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id || column.optionName}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 343 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import { Select } from 'src/common/components/Select'; import { Input } from 'src/common/components'; import { t, SupersetClient, styled } from '@superset-ui/core'; import adhocMetricType from 'src/explore/components/controls/MetricControl/adhocMetricType'; import columnType from 'src/explore/propTypes/columnType'; import { OPERATORS, OPERATORS_OPTIONS, TABLE_ONLY_OPERATORS, DRUID_ONLY_OPERATORS, HAVING_OPERATORS, MULTI_OPERATORS, CUSTOM_OPERATORS, DISABLE_INPUT_OPERATORS, } from 'src/explore/constants'; import FilterDefinitionOption from 'src/explore/components/controls/MetricControl/FilterDefinitionOption'; import AdhocFilter, { EXPRESSION_TYPES, CLAUSES } from './AdhocFilter'; const SelectWithLabel = styled(Select)` .ant-select-selector::after { content: '${({ labelText }) => labelText || '\\A0'}'; display: inline-block; white-space: nowrap; color: ${({ theme }) => theme.colors.grayscale.light1}; width: max-content; } `; const propTypes = { adhocFilter: PropTypes.instanceOf(AdhocFilter).isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf( PropTypes.oneOfType([ columnType, PropTypes.shape({ saved_metric_name: PropTypes.string.isRequired }), adhocMetricType, ]), ).isRequired, onHeightChange: PropTypes.func.isRequired, datasource: PropTypes.object, partitionColumn: PropTypes.string, popoverRef: PropTypes.object, }; const defaultProps = { datasource: {}, }; function translateOperator(operator) { if (operator === OPERATORS['==']) { return 'equals'; } if (operator === OPERATORS['!=']) { return 'not equal to'; } if (operator === OPERATORS.LIKE) { return 'LIKE'; } if (operator === OPERATORS['LATEST PARTITION']) { return 'use latest_partition template'; } return operator; } export default class AdhocFilterEditPopoverSimpleTabContent extends React.Component { constructor(props) { super(props); this.onSubjectChange = this.onSubjectChange.bind(this); this.onOperatorChange = this.onOperatorChange.bind(this); this.onComparatorChange = this.onComparatorChange.bind(this); this.onInputComparatorChange = this.onInputComparatorChange.bind(this); this.isOperatorRelevant = this.isOperatorRelevant.bind(this); this.refreshComparatorSuggestions = this.refreshComparatorSuggestions.bind( this, ); this.state = { suggestions: [], abortActiveRequest: null, }; this.selectProps = { name: 'select-column', showSearch: true, }; } UNSAFE_componentWillMount() { this.refreshComparatorSuggestions(); } componentDidUpdate(prevProps) { if (prevProps.adhocFilter.subject !== this.props.adhocFilter.subject) { this.refreshComparatorSuggestions(); } } onSubjectChange(id) { const option = this.props.options.find( option => option.id === id || option.optionName === id, ); let subject; let clause; // infer the new clause based on what subject was selected. if (option && option.column_name) { subject = option.column_name; clause = CLAUSES.WHERE; } else if (option && (option.saved_metric_name || option.label)) { subject = option.saved_metric_name || option.label; clause = CLAUSES.HAVING; } const { operator } = this.props.adhocFilter; this.props.onChange( this.props.adhocFilter.duplicateWith({ subject, clause, operator: operator && this.isOperatorRelevant(operator, subject) ? operator : null, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } onOperatorChange(operator) { const currentComparator = this.props.adhocFilter.comparator; let newComparator; // convert between list of comparators and individual comparators // (e.g. `in ('North America', 'Africa')` to `== 'North America'`) if (MULTI_OPERATORS.has(operator)) { newComparator = Array.isArray(currentComparator) ? currentComparator : [currentComparator].filter(element => element); } else { newComparator = Array.isArray(currentComparator) ? currentComparator[0] : currentComparator; } if (operator && CUSTOM_OPERATORS.has(operator)) { this.props.onChange( this.props.adhocFilter.duplicateWith({ subject: this.props.adhocFilter.subject, clause: CLAUSES.WHERE, operator, expressionType: EXPRESSION_TYPES.SQL, datasource: this.props.datasource, }), ); } else { this.props.onChange( this.props.adhocFilter.duplicateWith({ operator, comparator: newComparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } } onInputComparatorChange(event) { this.onComparatorChange(event.target.value); } onComparatorChange(comparator) { this.props.onChange( this.props.adhocFilter.duplicateWith({ comparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } refreshComparatorSuggestions() { const { datasource } = this.props; const col = this.props.adhocFilter.subject; const having = this.props.adhocFilter.clause === CLAUSES.HAVING; if (col && datasource && datasource.filter_select && !having) { if (this.state.abortActiveRequest) { this.state.abortActiveRequest(); } const controller = new AbortController(); const { signal } = controller; this.setState({ abortActiveRequest: controller.abort, loading: true }); SupersetClient.get({ signal, endpoint: `/superset/filter/${datasource.type}/${datasource.id}/${col}/`, }) .then(({ json }) => { this.setState(() => ({ suggestions: json, abortActiveRequest: null, loading: false, })); }) .catch(() => { this.setState(() => ({ suggestions: [], abortActiveRequest: null, loading: false, })); }); } } isOperatorRelevant(operator, subject) { if (operator && CUSTOM_OPERATORS.has(operator)) { const { partitionColumn } = this.props; return partitionColumn && subject && subject === partitionColumn; } return !( (this.props.datasource.type === 'druid' && TABLE_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.datasource.type === 'table' && DRUID_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.adhocFilter.clause === CLAUSES.HAVING && HAVING_OPERATORS.indexOf(operator) === -1) ); } focusComparator(ref, shouldFocus) { if (ref && shouldFocus) { ref.focus(); } } optionsRemaining() { const { suggestions } = this.state; const { comparator } = this.props.adhocFilter; // if select is multi/value is array, we show the options not selected const valuesFromSuggestionsLength = Array.isArray(comparator) ? comparator.filter(v => suggestions.includes(v)).length : 0; return suggestions?.length - valuesFromSuggestionsLength ?? 0; } createSuggestionsPlaceholder() { const optionsRemaining = this.optionsRemaining(); const placeholder = t('%s option(s)', optionsRemaining); return optionsRemaining ? placeholder : ''; } renderSubjectOptionLabel(option) { return <FilterDefinitionOption option={option} />; } render() { const { adhocFilter, options, datasource } = this.props; let columns = options; const { subject, operator, comparator } = adhocFilter; const subjectSelectProps = { value: subject ?? undefined, onChange: this.onSubjectChange, notFoundContent: t( 'No such column found. To filter on a metric, try the Custom SQL tab.', ), filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !subject, }; if (datasource.type === 'druid') { subjectSelectProps.placeholder = t( '%s column(s) and metric(s)', columns.length, ); } else { // we cannot support simple ad-hoc filters for metrics because we don't know what type // the value should be cast to (without knowing the output type of the aggregate, which // becomes a rather complicated problem) subjectSelectProps.placeholder = adhocFilter.clause === CLAUSES.WHERE ? t('%s column(s)', columns.length) : t('To filter on a metric, use Custom SQL tab.'); columns = options.filter(option => option.column_name); } const operatorSelectProps = { placeholder: t( '%s operator(s)', OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject)) .length, ), // like AGGREGTES_OPTIONS, operator options are string value: operator, onChange: this.onOperatorChange, filterOption: (input, option) => option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !!subjectSelectProps.value && !operator, }; const focusComparator = !!subjectSelectProps.value && !!operatorSelectProps.value; const comparatorSelectProps = { allowClear: true, showSearch: true, mode: MULTI_OPERATORS.has(operator) && 'tags', tokenSeparators: [',', '\n', '\t', ';'], loading: this.state.loading, value: comparator, onChange: this.onComparatorChange, notFoundContent: t('Type a value here'), disabled: DISABLE_INPUT_OPERATORS.includes(operator), placeholder: this.createSuggestionsPlaceholder(), labelText: comparator?.length > 0 && this.createSuggestionsPlaceholder(), autoFocus: focusComparator, }; return ( <> <FormGroup className="adhoc-filter-simple-column-dropdown"> <Select {...this.selectProps} {...subjectSelectProps} name="filter-column" > {columns.map(column => ( <Select.Option value={column.id || column.optionName} filterBy={ column.saved_metric_name || column.column_name || column.label } key={column.id || column.optionName} > {this.renderSubjectOptionLabel(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <Select {...this.selectProps} {...operatorSelectProps} name="filter-operator" > {OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject), ).map(option => ( <Select.Option value={option} key={option}> {translateOperator(option)} </Select.Option> ))} </Select> </FormGroup> <FormGroup data-test="adhoc-filter-simple-value"> {MULTI_OPERATORS.has(operator) || this.state.suggestions.length > 0 ? ( <SelectWithLabel name="filter-value" {...comparatorSelectProps}> {this.state.suggestions.map(suggestion => ( <Select.Option value={suggestion} key={suggestion}> {suggestion} </Select.Option> ))} </SelectWithLabel> ) : ( <Input name="filter-value" ref={ref => this.focusComparator(ref, focusComparator)} onChange={this.onInputComparatorChange} value={comparator} placeholder={t('Filter value (case sensitive)')} disabled={DISABLE_INPUT_OPERATORS.includes(operator)} /> )} </FormGroup> </> ); } } AdhocFilterEditPopoverSimpleTabContent.propTypes = propTypes; AdhocFilterEditPopoverSimpleTabContent.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.9975066781044006, 0.05939174443483353, 0.00016444711945950985, 0.0003029263752978295, 0.21988321840763092 ]
{ "id": 0, "code_window": [ " {...this.selectProps}\n", " {...subjectSelectProps}\n", " name=\"filter-column\"\n", " >\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id || column.optionName}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 343 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M4 5C4.55228 5 5 4.55228 5 4C5 3.44772 4.55228 3 4 3C3.44772 3 3 3.44772 3 4C3 4.55228 3.44772 5 4 5ZM4 9C4.55228 9 5 8.55228 5 8C5 7.44772 4.55228 7 4 7C3.44772 7 3 7.44772 3 8C3 8.55228 3.44772 9 4 9ZM9 4C9 4.55228 8.55228 5 8 5C7.44772 5 7 4.55228 7 4C7 3.44772 7.44772 3 8 3C8.55228 3 9 3.44772 9 4ZM12 5C12.5523 5 13 4.55228 13 4C13 3.44772 12.5523 3 12 3C11.4477 3 11 3.44772 11 4C11 4.55228 11.4477 5 12 5ZM17 4C17 4.55228 16.5523 5 16 5C15.4477 5 15 4.55228 15 4C15 3.44772 15.4477 3 16 3C16.5523 3 17 3.44772 17 4ZM20 5C20.5523 5 21 4.55228 21 4C21 3.44772 20.5523 3 20 3C19.4477 3 19 3.44772 19 4C19 4.55228 19.4477 5 20 5ZM21 8C21 8.55228 20.5523 9 20 9C19.4477 9 19 8.55228 19 8C19 7.44772 19.4477 7 20 7C20.5523 7 21 7.44772 21 8Z" fill="currentColor"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M4 11H20C20.5523 11 21 11.4477 21 12V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V12C3 11.4477 3.44772 11 4 11ZM5 13V19H19V13H5Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/components.svg
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.000180437506060116, 0.00017399205535184592, 0.00016675196820870042, 0.00017478664813097566, 0.000005615278951154323 ]
{ "id": 0, "code_window": [ " {...this.selectProps}\n", " {...subjectSelectProps}\n", " name=\"filter-column\"\n", " >\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id || column.optionName}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 343 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. slice_name: Number of Aspiring Developers viz_type: big_number_total params: adhoc_filters: - clause: WHERE comparator: '0' expressionType: SIMPLE filterOptionName: filter_3f8ug0vnqk1_oy0mvl0izdc isExtra: false isNew: false operator: == sqlExpression: null subject: is_software_dev datasource: 42__table granularity_sqla: time_start header_font_size: 0.4 metric: count queryFields: metric: metrics slice_id: 1363 subheader_font_size: 0.15 time_range: No filter time_range_endpoints: - inclusive - exclusive url_params: {} viz_type: big_number_total y_axis_format: SMART_NUMBER cache_timeout: null uuid: a0e5329f-224e-6fc8-efd2-d37d0f546ee8 version: 1.0.0 dataset_uuid: d95a2865-53ce-1f82-a53d-8e3c89331469
superset/examples/configs/charts/Number_of_Aspiring_Developers.yaml
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017871720774564892, 0.00017374793242197484, 0.00016485562082380056, 0.0001745784393278882, 0.000004906413778371643 ]
{ "id": 0, "code_window": [ " {...this.selectProps}\n", " {...subjectSelectProps}\n", " name=\"filter-column\"\n", " >\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id || column.optionName}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 343 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable no-unused-expressions */ import React from 'react'; import sinon from 'sinon'; import { shallow } from 'enzyme'; import { FormGroup } from 'react-bootstrap'; import AdhocFilter, { EXPRESSION_TYPES, CLAUSES, } from 'src/explore/components/controls/FilterControl/AdhocFilter'; import AdhocFilterEditPopoverSqlTabContent from 'src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent'; const sqlAdhocFilter = new AdhocFilter({ expressionType: EXPRESSION_TYPES.SQL, sqlExpression: 'value > 10', clause: CLAUSES.WHERE, }); function setup(overrides) { const onChange = sinon.spy(); const props = { adhocFilter: sqlAdhocFilter, onChange, options: [], height: 100, ...overrides, }; const wrapper = shallow(<AdhocFilterEditPopoverSqlTabContent {...props} />); return { wrapper, onChange }; } describe('AdhocFilterEditPopoverSqlTabContent', () => { it('renders the sql tab form', () => { const { wrapper } = setup(); expect(wrapper.find(FormGroup)).toHaveLength(2); }); it('passes the new clause to onChange after onSqlExpressionClauseChange', () => { const { wrapper, onChange } = setup(); wrapper.instance().onSqlExpressionClauseChange(CLAUSES.HAVING); expect(onChange.calledOnce).toBe(true); expect( onChange.lastCall.args[0].equals( sqlAdhocFilter.duplicateWith({ clause: CLAUSES.HAVING }), ), ).toBe(true); }); it('passes the new query to onChange after onSqlExpressionChange', () => { const { wrapper, onChange } = setup(); wrapper.instance().onSqlExpressionChange('value < 5'); expect(onChange.calledOnce).toBe(true); expect( onChange.lastCall.args[0].equals( sqlAdhocFilter.duplicateWith({ sqlExpression: 'value < 5' }), ), ).toBe(true); }); });
superset-frontend/spec/javascripts/explore/components/AdhocFilterEditPopoverSqlTabContent_spec.jsx
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017689923697616905, 0.0001728677743813023, 0.00016773093375377357, 0.000172687869053334, 0.0000028295901302044513 ]
{ "id": 1, "code_window": [ " <FormGroup>\n", " <Select\n", " {...this.selectProps}\n", " {...operatorSelectProps}\n", " name=\"filter-operator\"\n", " >\n", " {OPERATORS_OPTIONS.filter(op =>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 361 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import Tabs from 'src/common/components/Tabs'; import Button from 'src/components/Button'; import { Select } from 'src/common/components/Select'; import { styled, t } from '@superset-ui/core'; import { ColumnOption } from '@superset-ui/chart-controls'; import FormLabel from 'src/components/FormLabel'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import { noOp } from 'src/utils/common'; import { AGGREGATES_OPTIONS } from 'src/explore/constants'; import columnType from 'src/explore/propTypes/columnType'; import savedMetricType from './savedMetricType'; import AdhocMetric, { EXPRESSION_TYPES } from './AdhocMetric'; const propTypes = { adhocMetric: PropTypes.instanceOf(AdhocMetric).isRequired, onChange: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onResize: PropTypes.func.isRequired, getCurrentTab: PropTypes.func, getCurrentLabel: PropTypes.func, columns: PropTypes.arrayOf(columnType), savedMetricsOptions: PropTypes.arrayOf(savedMetricType), savedMetric: savedMetricType, datasourceType: PropTypes.string, }; const defaultProps = { columns: [], getCurrentTab: noOp, }; const ResizeIcon = styled.i` margin-left: ${({ theme }) => theme.gridUnit * 2}px; `; const ColumnOptionStyle = styled.span` .option-label { display: inline; } `; export const SAVED_TAB_KEY = 'SAVED'; const startingWidth = 320; const startingHeight = 240; export default class AdhocMetricEditPopover extends React.PureComponent { // "Saved" is a default tab unless there are no saved metrics for dataset defaultActiveTabKey = (this.props.savedMetric.metric_name || this.props.adhocMetric.isNew) && Array.isArray(this.props.savedMetricsOptions) && this.props.savedMetricsOptions.length > 0 ? SAVED_TAB_KEY : this.props.adhocMetric.expressionType; constructor(props) { super(props); this.onSave = this.onSave.bind(this); this.onResetStateAndClose = this.onResetStateAndClose.bind(this); this.onColumnChange = this.onColumnChange.bind(this); this.onAggregateChange = this.onAggregateChange.bind(this); this.onSavedMetricChange = this.onSavedMetricChange.bind(this); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onDragDown = this.onDragDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTabChange = this.onTabChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.refreshAceEditor = this.refreshAceEditor.bind(this); this.state = { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, width: startingWidth, height: startingHeight, }; document.addEventListener('mouseup', this.onMouseUp); } componentDidMount() { this.props.getCurrentTab(this.defaultActiveTabKey); } componentDidUpdate(prevProps, prevState) { if ( prevState.adhocMetric?.sqlExpression !== this.state.adhocMetric?.sqlExpression || prevState.adhocMetric?.aggregate !== this.state.adhocMetric?.aggregate || prevState.adhocMetric?.column?.column_name !== this.state.adhocMetric?.column?.column_name || prevState.savedMetric?.metric_name !== this.state.savedMetric?.metric_name ) { this.props.getCurrentLabel({ savedMetricLabel: this.state.savedMetric?.verbose_name || this.state.savedMetric?.metric_name, adhocMetricLabel: this.state.adhocMetric?.getDefaultLabel(), }); } } componentWillUnmount() { document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('mousemove', this.onMouseMove); } onSave() { const { adhocMetric, savedMetric } = this.state; const metric = savedMetric?.metric_name ? savedMetric : adhocMetric; const oldMetric = this.props.savedMetric?.metric_name ? this.props.savedMetric : this.props.adhocMetric; this.props.onChange( { ...metric, }, oldMetric, ); this.props.onClose(); } onResetStateAndClose() { this.setState( { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, }, this.props.onClose, ); } onColumnChange(columnId) { const column = this.props.columns.find(column => column.id === columnId); this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ column, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onAggregateChange(aggregate) { // we construct this object explicitly to overwrite the value in the case aggregate is null this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ aggregate, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onSavedMetricChange(savedMetricId) { const savedMetric = this.props.savedMetricsOptions.find( metric => metric.id === savedMetricId, ); this.setState(prevState => ({ savedMetric, adhocMetric: prevState.adhocMetric.duplicateWith({ column: undefined, aggregate: undefined, sqlExpression: undefined, expressionType: EXPRESSION_TYPES.SIMPLE, }), })); } onSqlExpressionChange(sqlExpression) { this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), savedMetric: undefined, })); } onDragDown(e) { this.dragStartX = e.clientX; this.dragStartY = e.clientY; this.dragStartWidth = this.state.width; this.dragStartHeight = this.state.height; document.addEventListener('mousemove', this.onMouseMove); } onMouseMove(e) { this.props.onResize(); this.setState({ width: Math.max( this.dragStartWidth + (e.clientX - this.dragStartX), startingWidth, ), height: Math.max( this.dragStartHeight + (e.clientY - this.dragStartY) * 2, startingHeight, ), }); } onMouseUp() { document.removeEventListener('mousemove', this.onMouseMove); } onTabChange(tab) { this.refreshAceEditor(); this.props.getCurrentTab(tab); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } refreshAceEditor() { setTimeout(() => { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } }, 0); } renderColumnOption(option) { const column = { ...option }; if (column.metric_name && !column.verbose_name) { column.verbose_name = column.metric_name; } return ( <ColumnOptionStyle> <ColumnOption column={column} showType /> </ColumnOptionStyle> ); } render() { const { adhocMetric: propsAdhocMetric, savedMetric: propsSavedMetric, columns, savedMetricsOptions, onChange, onClose, onResize, datasourceType, ...popoverProps } = this.props; const { adhocMetric, savedMetric } = this.state; const keywords = sqlKeywords.concat( columns.map(column => ({ name: column.column_name, value: column.column_name, score: 50, meta: 'column', })), ); const columnValue = (adhocMetric.column && adhocMetric.column.column_name) || adhocMetric.inferSqlExpressionColumn(); // autofocus on column if there's no value in column; otherwise autofocus on aggregate const columnSelectProps = { placeholder: t('%s column(s)', columns.length), value: columnValue, onChange: this.onColumnChange, allowClear: true, showSearch: true, autoFocus: !columnValue, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; const aggregateSelectProps = { placeholder: t('%s aggregates(s)', AGGREGATES_OPTIONS.length), value: adhocMetric.aggregate || adhocMetric.inferSqlExpressionAggregate(), onChange: this.onAggregateChange, allowClear: true, autoFocus: !!columnValue, showSearch: true, }; const savedSelectProps = { placeholder: t('%s saved metric(s)', savedMetricsOptions?.length ?? 0), value: savedMetric?.verbose_name || savedMetric?.metric_name, onChange: this.onSavedMetricChange, allowClear: true, showSearch: true, autoFocus: true, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; if (this.props.datasourceType === 'druid') { aggregateSelectProps.options = aggregateSelectProps.options.filter( aggregate => aggregate !== 'AVG', ); } const stateIsValid = adhocMetric.isValid() || savedMetric?.metric_name; const hasUnsavedChanges = !adhocMetric.equals(propsAdhocMetric) || (!( typeof savedMetric?.metric_name === 'undefined' && typeof propsSavedMetric?.metric_name === 'undefined' ) && savedMetric?.metric_name !== propsSavedMetric?.metric_name); return ( <div id="metrics-edit-popover" data-test="metrics-edit-popover" {...popoverProps} > <Tabs id="adhoc-metric-edit-tabs" data-test="adhoc-metric-edit-tabs" defaultActiveKey={this.defaultActiveTabKey} className="adhoc-metric-edit-tabs" style={{ height: this.state.height, width: this.state.width }} onChange={this.onTabChange} allowOverflow > <Tabs.TabPane key={SAVED_TAB_KEY} tab={t('Saved')}> <FormGroup> <FormLabel> <strong>{t('Saved metric')}</strong> </FormLabel> <Select name="select-saved" {...savedSelectProps}> {Array.isArray(savedMetricsOptions) && savedMetricsOptions.map(savedMetric => ( <Select.Option value={savedMetric.id} filterBy={ savedMetric.verbose_name || savedMetric.metric_name } key={savedMetric.id} > {this.renderColumnOption(savedMetric)} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}> <FormGroup> <FormLabel> <strong>{t('column')}</strong> </FormLabel> <Select name="select-column" {...columnSelectProps}> {columns.map(column => ( <Select.Option value={column.id} filterBy={column.verbose_name || column.column_name} key={column.id} > {this.renderColumnOption(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <FormLabel> <strong>{t('aggregate')}</strong> </FormLabel> <Select name="select-aggregate" {...aggregateSelectProps}> {AGGREGATES_OPTIONS.map(option => ( <Select.Option value={option} key={option}> {option} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SQL} tab={t('Custom SQL')} data-test="adhoc-metric-edit-tab#custom" > {this.props.datasourceType !== 'druid' ? ( <FormGroup data-test="sql-editor"> <SQLEditor showLoadingForImport ref={this.handleAceEditorRef} keywords={keywords} height={`${this.state.height - 80}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={ adhocMetric.sqlExpression || adhocMetric.translateToSql() } editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="adhoc-filter-sql-editor" wrapEnabled /> </FormGroup> ) : ( <div className="custom-sql-disabled-message"> Custom SQL Metrics are not available on druid datasources </div> )} </Tabs.TabPane> </Tabs> <div> <Button buttonSize="small" onClick={this.onResetStateAndClose} data-test="AdhocMetricEdit#cancel" cta > {t('Close')} </Button> <Button disabled={!stateIsValid} buttonStyle={ hasUnsavedChanges && stateIsValid ? 'primary' : 'default' } buttonSize="small" data-test="AdhocMetricEdit#save" onClick={this.onSave} cta > {t('Save')} </Button> <ResizeIcon role="button" aria-label="Resize" tabIndex={0} onMouseDown={this.onDragDown} className="fa fa-expand edit-popover-resize text-muted" /> </div> </div> ); } } AdhocMetricEditPopover.propTypes = propTypes; AdhocMetricEditPopover.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0018766258144751191, 0.0003761256521102041, 0.00016446215158794075, 0.00017475416825618595, 0.0004443602520041168 ]
{ "id": 1, "code_window": [ " <FormGroup>\n", " <Select\n", " {...this.selectProps}\n", " {...operatorSelectProps}\n", " name=\"filter-operator\"\n", " >\n", " {OPERATORS_OPTIONS.filter(op =>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 361 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { DASHBOARD_ROOT_TYPE, DASHBOARD_GRID_TYPE } from './componentTypes'; import { DASHBOARD_GRID_ID, DASHBOARD_ROOT_ID, DASHBOARD_VERSION_KEY, } from './constants'; export default function getEmptyLayout() { return { [DASHBOARD_VERSION_KEY]: 'v2', [DASHBOARD_ROOT_ID]: { type: DASHBOARD_ROOT_TYPE, id: DASHBOARD_ROOT_ID, children: [DASHBOARD_GRID_ID], }, [DASHBOARD_GRID_ID]: { type: DASHBOARD_GRID_TYPE, id: DASHBOARD_GRID_ID, children: [], parents: [DASHBOARD_ROOT_ID], }, }; }
superset-frontend/src/dashboard/util/getEmptyLayout.js
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017607970221433789, 0.00017312608542852104, 0.00017034212942235172, 0.00017399813805241138, 0.000002324404022147064 ]
{ "id": 1, "code_window": [ " <FormGroup>\n", " <Select\n", " {...this.selectProps}\n", " {...operatorSelectProps}\n", " name=\"filter-operator\"\n", " >\n", " {OPERATORS_OPTIONS.filter(op =>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 361 }
{# Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. #} {% extends "appbuilder/base.html" %} {% block title %}{{ _("Import dashboards") }}{% endblock %} {% block content %} <div class="container"> <div class="panel"> <div class="panel-heading"><h3>{{ _("Import Dashboard(s)") }}</h3></div> <div class="panel-body"> <form method="post" enctype="multipart/form-data"> <input type="hidden" name="csrf_token" id="csrf_token" value="{{ csrf_token() if csrf_token else '' }}" /> <table class="table table-bordered"> <tr> <td>{{ _("File") }}</td> <td> <label class="btn btn-default btn-sm" for="my-file-selector"> <input id="my-file-selector" type="file" name="file" accept=".json" style="display:none;" onchange="$('#upload-file-info').html(this.files[0].name)"/> {{ _("Choose File") }} </label> <span class='label label-info' id="upload-file-info"></span> </td> </tr> <tr> <td>{{ _("Database") }}</td> <td> <select id="db_id" name="db_id" class="form-control input-sm" style="width: 300px"> {% for db in databases %} <option value="{{ db.id }}">{{ db.name }}</option> {% endfor %} </select> </td> </tr> </table> <input type="submit" value="{{ _("Upload") }}" class="btn btn-primary btn-sm" /> </form> </div> </div> </div> {% endblock %}
superset/templates/superset/import_dashboards.html
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0001796233409550041, 0.00017315021250396967, 0.00016860337927937508, 0.00017108047904912382, 0.000004584623184200609 ]
{ "id": 1, "code_window": [ " <FormGroup>\n", " <Select\n", " {...this.selectProps}\n", " {...operatorSelectProps}\n", " name=\"filter-operator\"\n", " >\n", " {OPERATORS_OPTIONS.filter(op =>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "add", "edit_start_line_idx": 361 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from unittest import skipUnless from superset import is_feature_enabled from tests.base_tests import SupersetTestCase class TestTagging(SupersetTestCase): @skipUnless( (is_feature_enabled("TAGGING_SYSTEM") == False), "skipping as tagging endpoints are not enabled", ) def test_tag_view_attachment_disabled(self): response = self.client.get("/tagview/tagged_objects/") self.assertEqual(404, response.status_code) @skipUnless( is_feature_enabled("TAGGING_SYSTEM"), "skipping as tagging endpoints are enabled", ) def test_tag_view_attachment_enabled(self): response = self.client.get("/tagview/tagged_objects/") self.assertEqual(200, response.status_code)
tests/tagging_tests.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017623086750973016, 0.00017325137741863728, 0.00016871708794496953, 0.00017402878438588232, 0.00000317010471917456 ]
{ "id": 2, "code_window": [ " <FormGroup data-test=\"adhoc-filter-simple-value\">\n", " {MULTI_OPERATORS.has(operator) ||\n", " this.state.suggestions.length > 0 ? (\n", " <SelectWithLabel name=\"filter-value\" {...comparatorSelectProps}>\n", " {this.state.suggestions.map(suggestion => (\n", " <Select.Option value={suggestion} key={suggestion}>\n", " {suggestion}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SelectWithLabel\n", " name=\"filter-value\"\n", " {...comparatorSelectProps}\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "replace", "edit_start_line_idx": 375 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import Tabs from 'src/common/components/Tabs'; import Button from 'src/components/Button'; import { Select } from 'src/common/components/Select'; import { styled, t } from '@superset-ui/core'; import { ColumnOption } from '@superset-ui/chart-controls'; import FormLabel from 'src/components/FormLabel'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import { noOp } from 'src/utils/common'; import { AGGREGATES_OPTIONS } from 'src/explore/constants'; import columnType from 'src/explore/propTypes/columnType'; import savedMetricType from './savedMetricType'; import AdhocMetric, { EXPRESSION_TYPES } from './AdhocMetric'; const propTypes = { adhocMetric: PropTypes.instanceOf(AdhocMetric).isRequired, onChange: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onResize: PropTypes.func.isRequired, getCurrentTab: PropTypes.func, getCurrentLabel: PropTypes.func, columns: PropTypes.arrayOf(columnType), savedMetricsOptions: PropTypes.arrayOf(savedMetricType), savedMetric: savedMetricType, datasourceType: PropTypes.string, }; const defaultProps = { columns: [], getCurrentTab: noOp, }; const ResizeIcon = styled.i` margin-left: ${({ theme }) => theme.gridUnit * 2}px; `; const ColumnOptionStyle = styled.span` .option-label { display: inline; } `; export const SAVED_TAB_KEY = 'SAVED'; const startingWidth = 320; const startingHeight = 240; export default class AdhocMetricEditPopover extends React.PureComponent { // "Saved" is a default tab unless there are no saved metrics for dataset defaultActiveTabKey = (this.props.savedMetric.metric_name || this.props.adhocMetric.isNew) && Array.isArray(this.props.savedMetricsOptions) && this.props.savedMetricsOptions.length > 0 ? SAVED_TAB_KEY : this.props.adhocMetric.expressionType; constructor(props) { super(props); this.onSave = this.onSave.bind(this); this.onResetStateAndClose = this.onResetStateAndClose.bind(this); this.onColumnChange = this.onColumnChange.bind(this); this.onAggregateChange = this.onAggregateChange.bind(this); this.onSavedMetricChange = this.onSavedMetricChange.bind(this); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onDragDown = this.onDragDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTabChange = this.onTabChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.refreshAceEditor = this.refreshAceEditor.bind(this); this.state = { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, width: startingWidth, height: startingHeight, }; document.addEventListener('mouseup', this.onMouseUp); } componentDidMount() { this.props.getCurrentTab(this.defaultActiveTabKey); } componentDidUpdate(prevProps, prevState) { if ( prevState.adhocMetric?.sqlExpression !== this.state.adhocMetric?.sqlExpression || prevState.adhocMetric?.aggregate !== this.state.adhocMetric?.aggregate || prevState.adhocMetric?.column?.column_name !== this.state.adhocMetric?.column?.column_name || prevState.savedMetric?.metric_name !== this.state.savedMetric?.metric_name ) { this.props.getCurrentLabel({ savedMetricLabel: this.state.savedMetric?.verbose_name || this.state.savedMetric?.metric_name, adhocMetricLabel: this.state.adhocMetric?.getDefaultLabel(), }); } } componentWillUnmount() { document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('mousemove', this.onMouseMove); } onSave() { const { adhocMetric, savedMetric } = this.state; const metric = savedMetric?.metric_name ? savedMetric : adhocMetric; const oldMetric = this.props.savedMetric?.metric_name ? this.props.savedMetric : this.props.adhocMetric; this.props.onChange( { ...metric, }, oldMetric, ); this.props.onClose(); } onResetStateAndClose() { this.setState( { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, }, this.props.onClose, ); } onColumnChange(columnId) { const column = this.props.columns.find(column => column.id === columnId); this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ column, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onAggregateChange(aggregate) { // we construct this object explicitly to overwrite the value in the case aggregate is null this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ aggregate, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onSavedMetricChange(savedMetricId) { const savedMetric = this.props.savedMetricsOptions.find( metric => metric.id === savedMetricId, ); this.setState(prevState => ({ savedMetric, adhocMetric: prevState.adhocMetric.duplicateWith({ column: undefined, aggregate: undefined, sqlExpression: undefined, expressionType: EXPRESSION_TYPES.SIMPLE, }), })); } onSqlExpressionChange(sqlExpression) { this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), savedMetric: undefined, })); } onDragDown(e) { this.dragStartX = e.clientX; this.dragStartY = e.clientY; this.dragStartWidth = this.state.width; this.dragStartHeight = this.state.height; document.addEventListener('mousemove', this.onMouseMove); } onMouseMove(e) { this.props.onResize(); this.setState({ width: Math.max( this.dragStartWidth + (e.clientX - this.dragStartX), startingWidth, ), height: Math.max( this.dragStartHeight + (e.clientY - this.dragStartY) * 2, startingHeight, ), }); } onMouseUp() { document.removeEventListener('mousemove', this.onMouseMove); } onTabChange(tab) { this.refreshAceEditor(); this.props.getCurrentTab(tab); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } refreshAceEditor() { setTimeout(() => { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } }, 0); } renderColumnOption(option) { const column = { ...option }; if (column.metric_name && !column.verbose_name) { column.verbose_name = column.metric_name; } return ( <ColumnOptionStyle> <ColumnOption column={column} showType /> </ColumnOptionStyle> ); } render() { const { adhocMetric: propsAdhocMetric, savedMetric: propsSavedMetric, columns, savedMetricsOptions, onChange, onClose, onResize, datasourceType, ...popoverProps } = this.props; const { adhocMetric, savedMetric } = this.state; const keywords = sqlKeywords.concat( columns.map(column => ({ name: column.column_name, value: column.column_name, score: 50, meta: 'column', })), ); const columnValue = (adhocMetric.column && adhocMetric.column.column_name) || adhocMetric.inferSqlExpressionColumn(); // autofocus on column if there's no value in column; otherwise autofocus on aggregate const columnSelectProps = { placeholder: t('%s column(s)', columns.length), value: columnValue, onChange: this.onColumnChange, allowClear: true, showSearch: true, autoFocus: !columnValue, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; const aggregateSelectProps = { placeholder: t('%s aggregates(s)', AGGREGATES_OPTIONS.length), value: adhocMetric.aggregate || adhocMetric.inferSqlExpressionAggregate(), onChange: this.onAggregateChange, allowClear: true, autoFocus: !!columnValue, showSearch: true, }; const savedSelectProps = { placeholder: t('%s saved metric(s)', savedMetricsOptions?.length ?? 0), value: savedMetric?.verbose_name || savedMetric?.metric_name, onChange: this.onSavedMetricChange, allowClear: true, showSearch: true, autoFocus: true, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; if (this.props.datasourceType === 'druid') { aggregateSelectProps.options = aggregateSelectProps.options.filter( aggregate => aggregate !== 'AVG', ); } const stateIsValid = adhocMetric.isValid() || savedMetric?.metric_name; const hasUnsavedChanges = !adhocMetric.equals(propsAdhocMetric) || (!( typeof savedMetric?.metric_name === 'undefined' && typeof propsSavedMetric?.metric_name === 'undefined' ) && savedMetric?.metric_name !== propsSavedMetric?.metric_name); return ( <div id="metrics-edit-popover" data-test="metrics-edit-popover" {...popoverProps} > <Tabs id="adhoc-metric-edit-tabs" data-test="adhoc-metric-edit-tabs" defaultActiveKey={this.defaultActiveTabKey} className="adhoc-metric-edit-tabs" style={{ height: this.state.height, width: this.state.width }} onChange={this.onTabChange} allowOverflow > <Tabs.TabPane key={SAVED_TAB_KEY} tab={t('Saved')}> <FormGroup> <FormLabel> <strong>{t('Saved metric')}</strong> </FormLabel> <Select name="select-saved" {...savedSelectProps}> {Array.isArray(savedMetricsOptions) && savedMetricsOptions.map(savedMetric => ( <Select.Option value={savedMetric.id} filterBy={ savedMetric.verbose_name || savedMetric.metric_name } key={savedMetric.id} > {this.renderColumnOption(savedMetric)} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}> <FormGroup> <FormLabel> <strong>{t('column')}</strong> </FormLabel> <Select name="select-column" {...columnSelectProps}> {columns.map(column => ( <Select.Option value={column.id} filterBy={column.verbose_name || column.column_name} key={column.id} > {this.renderColumnOption(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <FormLabel> <strong>{t('aggregate')}</strong> </FormLabel> <Select name="select-aggregate" {...aggregateSelectProps}> {AGGREGATES_OPTIONS.map(option => ( <Select.Option value={option} key={option}> {option} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SQL} tab={t('Custom SQL')} data-test="adhoc-metric-edit-tab#custom" > {this.props.datasourceType !== 'druid' ? ( <FormGroup data-test="sql-editor"> <SQLEditor showLoadingForImport ref={this.handleAceEditorRef} keywords={keywords} height={`${this.state.height - 80}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={ adhocMetric.sqlExpression || adhocMetric.translateToSql() } editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="adhoc-filter-sql-editor" wrapEnabled /> </FormGroup> ) : ( <div className="custom-sql-disabled-message"> Custom SQL Metrics are not available on druid datasources </div> )} </Tabs.TabPane> </Tabs> <div> <Button buttonSize="small" onClick={this.onResetStateAndClose} data-test="AdhocMetricEdit#cancel" cta > {t('Close')} </Button> <Button disabled={!stateIsValid} buttonStyle={ hasUnsavedChanges && stateIsValid ? 'primary' : 'default' } buttonSize="small" data-test="AdhocMetricEdit#save" onClick={this.onSave} cta > {t('Save')} </Button> <ResizeIcon role="button" aria-label="Resize" tabIndex={0} onMouseDown={this.onDragDown} className="fa fa-expand edit-popover-resize text-muted" /> </div> </div> ); } } AdhocMetricEditPopover.propTypes = propTypes; AdhocMetricEditPopover.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0125254075974226, 0.0005663123447448015, 0.00016166630666702986, 0.00017646509513724595, 0.0017864905530586839 ]
{ "id": 2, "code_window": [ " <FormGroup data-test=\"adhoc-filter-simple-value\">\n", " {MULTI_OPERATORS.has(operator) ||\n", " this.state.suggestions.length > 0 ? (\n", " <SelectWithLabel name=\"filter-value\" {...comparatorSelectProps}>\n", " {this.state.suggestions.map(suggestion => (\n", " <Select.Option value={suggestion} key={suggestion}>\n", " {suggestion}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SelectWithLabel\n", " name=\"filter-value\"\n", " {...comparatorSelectProps}\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "replace", "edit_start_line_idx": 375 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from flask import Flask from flask_caching import Cache from werkzeug.wrappers import Response CacheConfig = Union[Callable[[Flask], Cache], Dict[str, Any]] DbapiDescriptionRow = Tuple[ str, str, Optional[str], Optional[str], Optional[int], Optional[int], bool ] DbapiDescription = Union[List[DbapiDescriptionRow], Tuple[DbapiDescriptionRow, ...]] DbapiResult = Sequence[Union[List[Any], Tuple[Any, ...]]] FilterValue = Union[float, int, str] FilterValues = Union[FilterValue, List[FilterValue], Tuple[FilterValue]] FormData = Dict[str, Any] Granularity = Union[str, Dict[str, Union[str, float]]] Metric = Union[Dict[str, str], str] QueryObjectDict = Dict[str, Any] VizData = Optional[Union[List[Any], Dict[Any, Any]]] VizPayload = Dict[str, Any] # Flask response. Base = Union[bytes, str] Status = Union[int, str] Headers = Dict[str, Any] FlaskResponse = Union[ Response, Base, Tuple[Base, Status], Tuple[Base, Status, Headers], ]
superset/typing.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0006104189669713378, 0.0002675951400306076, 0.00016364091425202787, 0.0001776859862729907, 0.00017208022472914308 ]
{ "id": 2, "code_window": [ " <FormGroup data-test=\"adhoc-filter-simple-value\">\n", " {MULTI_OPERATORS.has(operator) ||\n", " this.state.suggestions.length > 0 ? (\n", " <SelectWithLabel name=\"filter-value\" {...comparatorSelectProps}>\n", " {this.state.suggestions.map(suggestion => (\n", " <Select.Option value={suggestion} key={suggestion}>\n", " {suggestion}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SelectWithLabel\n", " name=\"filter-value\"\n", " {...comparatorSelectProps}\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "replace", "edit_start_line_idx": 375 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.1808 8.17033C11.5789 7.60162 12.4211 7.60161 12.8192 8.17033L17.8986 15.4265C18.3625 16.0893 17.8884 17 17.0793 17H6.92066C6.11163 17 5.63748 16.0893 6.10142 15.4265L11.1808 8.17033Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/triangle_change.svg
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0001792353141354397, 0.00017623044550418854, 0.00017271410615649074, 0.0001767419307725504, 0.000002686726247702609 ]
{ "id": 2, "code_window": [ " <FormGroup data-test=\"adhoc-filter-simple-value\">\n", " {MULTI_OPERATORS.has(operator) ||\n", " this.state.suggestions.length > 0 ? (\n", " <SelectWithLabel name=\"filter-value\" {...comparatorSelectProps}>\n", " {this.state.suggestions.map(suggestion => (\n", " <Select.Option value={suggestion} key={suggestion}>\n", " {suggestion}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <SelectWithLabel\n", " name=\"filter-value\"\n", " {...comparatorSelectProps}\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx", "type": "replace", "edit_start_line_idx": 375 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable no-unused-expressions */ import React from 'react'; import { shallow } from 'enzyme'; import AggregateOption from 'src/explore/components/AggregateOption'; describe('AggregateOption', () => { it('renders the aggregate', () => { const wrapper = shallow( <AggregateOption aggregate={{ aggregate_name: 'SUM' }} />, ); expect(wrapper.text()).toBe('SUM'); }); });
superset-frontend/spec/javascripts/explore/components/AggregateOption_spec.jsx
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.000175176071934402, 0.00017269326781388372, 0.0001706920302240178, 0.0001724524627206847, 0.000001910204900923418 ]
{ "id": 3, "code_window": [ " {...this.selectProps}\n", " {...clauseSelectProps}\n", " className=\"filter-edit-clause-dropdown\"\n", " >\n", " {Object.keys(CLAUSES).map(clause => (\n", " <Select.Option value={clause} key={clause}>\n", " {clause}\n", " </Select.Option>\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent.jsx", "type": "add", "edit_start_line_idx": 118 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import Tabs from 'src/common/components/Tabs'; import Button from 'src/components/Button'; import { Select } from 'src/common/components/Select'; import { styled, t } from '@superset-ui/core'; import { ColumnOption } from '@superset-ui/chart-controls'; import FormLabel from 'src/components/FormLabel'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import { noOp } from 'src/utils/common'; import { AGGREGATES_OPTIONS } from 'src/explore/constants'; import columnType from 'src/explore/propTypes/columnType'; import savedMetricType from './savedMetricType'; import AdhocMetric, { EXPRESSION_TYPES } from './AdhocMetric'; const propTypes = { adhocMetric: PropTypes.instanceOf(AdhocMetric).isRequired, onChange: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onResize: PropTypes.func.isRequired, getCurrentTab: PropTypes.func, getCurrentLabel: PropTypes.func, columns: PropTypes.arrayOf(columnType), savedMetricsOptions: PropTypes.arrayOf(savedMetricType), savedMetric: savedMetricType, datasourceType: PropTypes.string, }; const defaultProps = { columns: [], getCurrentTab: noOp, }; const ResizeIcon = styled.i` margin-left: ${({ theme }) => theme.gridUnit * 2}px; `; const ColumnOptionStyle = styled.span` .option-label { display: inline; } `; export const SAVED_TAB_KEY = 'SAVED'; const startingWidth = 320; const startingHeight = 240; export default class AdhocMetricEditPopover extends React.PureComponent { // "Saved" is a default tab unless there are no saved metrics for dataset defaultActiveTabKey = (this.props.savedMetric.metric_name || this.props.adhocMetric.isNew) && Array.isArray(this.props.savedMetricsOptions) && this.props.savedMetricsOptions.length > 0 ? SAVED_TAB_KEY : this.props.adhocMetric.expressionType; constructor(props) { super(props); this.onSave = this.onSave.bind(this); this.onResetStateAndClose = this.onResetStateAndClose.bind(this); this.onColumnChange = this.onColumnChange.bind(this); this.onAggregateChange = this.onAggregateChange.bind(this); this.onSavedMetricChange = this.onSavedMetricChange.bind(this); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onDragDown = this.onDragDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTabChange = this.onTabChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.refreshAceEditor = this.refreshAceEditor.bind(this); this.state = { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, width: startingWidth, height: startingHeight, }; document.addEventListener('mouseup', this.onMouseUp); } componentDidMount() { this.props.getCurrentTab(this.defaultActiveTabKey); } componentDidUpdate(prevProps, prevState) { if ( prevState.adhocMetric?.sqlExpression !== this.state.adhocMetric?.sqlExpression || prevState.adhocMetric?.aggregate !== this.state.adhocMetric?.aggregate || prevState.adhocMetric?.column?.column_name !== this.state.adhocMetric?.column?.column_name || prevState.savedMetric?.metric_name !== this.state.savedMetric?.metric_name ) { this.props.getCurrentLabel({ savedMetricLabel: this.state.savedMetric?.verbose_name || this.state.savedMetric?.metric_name, adhocMetricLabel: this.state.adhocMetric?.getDefaultLabel(), }); } } componentWillUnmount() { document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('mousemove', this.onMouseMove); } onSave() { const { adhocMetric, savedMetric } = this.state; const metric = savedMetric?.metric_name ? savedMetric : adhocMetric; const oldMetric = this.props.savedMetric?.metric_name ? this.props.savedMetric : this.props.adhocMetric; this.props.onChange( { ...metric, }, oldMetric, ); this.props.onClose(); } onResetStateAndClose() { this.setState( { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, }, this.props.onClose, ); } onColumnChange(columnId) { const column = this.props.columns.find(column => column.id === columnId); this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ column, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onAggregateChange(aggregate) { // we construct this object explicitly to overwrite the value in the case aggregate is null this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ aggregate, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onSavedMetricChange(savedMetricId) { const savedMetric = this.props.savedMetricsOptions.find( metric => metric.id === savedMetricId, ); this.setState(prevState => ({ savedMetric, adhocMetric: prevState.adhocMetric.duplicateWith({ column: undefined, aggregate: undefined, sqlExpression: undefined, expressionType: EXPRESSION_TYPES.SIMPLE, }), })); } onSqlExpressionChange(sqlExpression) { this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), savedMetric: undefined, })); } onDragDown(e) { this.dragStartX = e.clientX; this.dragStartY = e.clientY; this.dragStartWidth = this.state.width; this.dragStartHeight = this.state.height; document.addEventListener('mousemove', this.onMouseMove); } onMouseMove(e) { this.props.onResize(); this.setState({ width: Math.max( this.dragStartWidth + (e.clientX - this.dragStartX), startingWidth, ), height: Math.max( this.dragStartHeight + (e.clientY - this.dragStartY) * 2, startingHeight, ), }); } onMouseUp() { document.removeEventListener('mousemove', this.onMouseMove); } onTabChange(tab) { this.refreshAceEditor(); this.props.getCurrentTab(tab); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } refreshAceEditor() { setTimeout(() => { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } }, 0); } renderColumnOption(option) { const column = { ...option }; if (column.metric_name && !column.verbose_name) { column.verbose_name = column.metric_name; } return ( <ColumnOptionStyle> <ColumnOption column={column} showType /> </ColumnOptionStyle> ); } render() { const { adhocMetric: propsAdhocMetric, savedMetric: propsSavedMetric, columns, savedMetricsOptions, onChange, onClose, onResize, datasourceType, ...popoverProps } = this.props; const { adhocMetric, savedMetric } = this.state; const keywords = sqlKeywords.concat( columns.map(column => ({ name: column.column_name, value: column.column_name, score: 50, meta: 'column', })), ); const columnValue = (adhocMetric.column && adhocMetric.column.column_name) || adhocMetric.inferSqlExpressionColumn(); // autofocus on column if there's no value in column; otherwise autofocus on aggregate const columnSelectProps = { placeholder: t('%s column(s)', columns.length), value: columnValue, onChange: this.onColumnChange, allowClear: true, showSearch: true, autoFocus: !columnValue, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; const aggregateSelectProps = { placeholder: t('%s aggregates(s)', AGGREGATES_OPTIONS.length), value: adhocMetric.aggregate || adhocMetric.inferSqlExpressionAggregate(), onChange: this.onAggregateChange, allowClear: true, autoFocus: !!columnValue, showSearch: true, }; const savedSelectProps = { placeholder: t('%s saved metric(s)', savedMetricsOptions?.length ?? 0), value: savedMetric?.verbose_name || savedMetric?.metric_name, onChange: this.onSavedMetricChange, allowClear: true, showSearch: true, autoFocus: true, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; if (this.props.datasourceType === 'druid') { aggregateSelectProps.options = aggregateSelectProps.options.filter( aggregate => aggregate !== 'AVG', ); } const stateIsValid = adhocMetric.isValid() || savedMetric?.metric_name; const hasUnsavedChanges = !adhocMetric.equals(propsAdhocMetric) || (!( typeof savedMetric?.metric_name === 'undefined' && typeof propsSavedMetric?.metric_name === 'undefined' ) && savedMetric?.metric_name !== propsSavedMetric?.metric_name); return ( <div id="metrics-edit-popover" data-test="metrics-edit-popover" {...popoverProps} > <Tabs id="adhoc-metric-edit-tabs" data-test="adhoc-metric-edit-tabs" defaultActiveKey={this.defaultActiveTabKey} className="adhoc-metric-edit-tabs" style={{ height: this.state.height, width: this.state.width }} onChange={this.onTabChange} allowOverflow > <Tabs.TabPane key={SAVED_TAB_KEY} tab={t('Saved')}> <FormGroup> <FormLabel> <strong>{t('Saved metric')}</strong> </FormLabel> <Select name="select-saved" {...savedSelectProps}> {Array.isArray(savedMetricsOptions) && savedMetricsOptions.map(savedMetric => ( <Select.Option value={savedMetric.id} filterBy={ savedMetric.verbose_name || savedMetric.metric_name } key={savedMetric.id} > {this.renderColumnOption(savedMetric)} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}> <FormGroup> <FormLabel> <strong>{t('column')}</strong> </FormLabel> <Select name="select-column" {...columnSelectProps}> {columns.map(column => ( <Select.Option value={column.id} filterBy={column.verbose_name || column.column_name} key={column.id} > {this.renderColumnOption(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <FormLabel> <strong>{t('aggregate')}</strong> </FormLabel> <Select name="select-aggregate" {...aggregateSelectProps}> {AGGREGATES_OPTIONS.map(option => ( <Select.Option value={option} key={option}> {option} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SQL} tab={t('Custom SQL')} data-test="adhoc-metric-edit-tab#custom" > {this.props.datasourceType !== 'druid' ? ( <FormGroup data-test="sql-editor"> <SQLEditor showLoadingForImport ref={this.handleAceEditorRef} keywords={keywords} height={`${this.state.height - 80}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={ adhocMetric.sqlExpression || adhocMetric.translateToSql() } editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="adhoc-filter-sql-editor" wrapEnabled /> </FormGroup> ) : ( <div className="custom-sql-disabled-message"> Custom SQL Metrics are not available on druid datasources </div> )} </Tabs.TabPane> </Tabs> <div> <Button buttonSize="small" onClick={this.onResetStateAndClose} data-test="AdhocMetricEdit#cancel" cta > {t('Close')} </Button> <Button disabled={!stateIsValid} buttonStyle={ hasUnsavedChanges && stateIsValid ? 'primary' : 'default' } buttonSize="small" data-test="AdhocMetricEdit#save" onClick={this.onSave} cta > {t('Save')} </Button> <ResizeIcon role="button" aria-label="Resize" tabIndex={0} onMouseDown={this.onDragDown} className="fa fa-expand edit-popover-resize text-muted" /> </div> </div> ); } } AdhocMetricEditPopover.propTypes = propTypes; AdhocMetricEditPopover.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.013446751050651073, 0.001000671647489071, 0.0001610428880667314, 0.00017643984756432474, 0.0025221325922757387 ]
{ "id": 3, "code_window": [ " {...this.selectProps}\n", " {...clauseSelectProps}\n", " className=\"filter-edit-clause-dropdown\"\n", " >\n", " {Object.keys(CLAUSES).map(clause => (\n", " <Select.Option value={clause} key={clause}>\n", " {clause}\n", " </Select.Option>\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent.jsx", "type": "add", "edit_start_line_idx": 118 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint camelcase: 0 */ export function formatSelectOptions(options) { return options.map(opt => [opt, opt.toString()]); } export function getDatasourceParameter(datasourceId, datasourceType) { return `${datasourceId}__${datasourceType}`; } export function getParam(name) { /* eslint no-useless-escape: 0 */ const formattedName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); const regex = new RegExp(`[\\?&]${formattedName}=([^&#]*)`); const results = regex.exec(window.location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); } export function mainMetric(savedMetrics) { // Using 'count' as default metric if it exists, otherwise using whatever one shows up first let metric; if (savedMetrics && savedMetrics.length > 0) { savedMetrics.forEach(m => { if (m.metric_name === 'count') { metric = 'count'; } }); if (!metric) { metric = savedMetrics[0].metric_name; } } return metric; }
superset-frontend/src/modules/utils.js
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00045408730511553586, 0.00022108345001470298, 0.00017252235556952655, 0.0001751257514115423, 0.00010421648767078295 ]
{ "id": 3, "code_window": [ " {...this.selectProps}\n", " {...clauseSelectProps}\n", " className=\"filter-edit-clause-dropdown\"\n", " >\n", " {Object.keys(CLAUSES).map(clause => (\n", " <Select.Option value={clause} key={clause}>\n", " {clause}\n", " </Select.Option>\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent.jsx", "type": "add", "edit_start_line_idx": 118 }
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # **/__pycache__/ **/.mypy_cache **/.pytest_cache **/.tox **/.vscode **/.idea **/.coverage **/.DS_Store **/.eggs **/.python-version **/*.egg-info **/*.bak **/*.db **/*.pyc **/*.sqllite **/*.swp tests/ docs/ install/ superset-frontend/node_modules/ superset-frontend/cypress/ superset-frontend/coverage/ venv
.dockerignore
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017870613373816013, 0.00017379276687279344, 0.00016838456213008612, 0.0001744307082844898, 0.0000038738098737667315 ]
{ "id": 3, "code_window": [ " {...this.selectProps}\n", " {...clauseSelectProps}\n", " className=\"filter-edit-clause-dropdown\"\n", " >\n", " {Object.keys(CLAUSES).map(clause => (\n", " <Select.Option value={clause} key={clause}>\n", " {clause}\n", " </Select.Option>\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " getPopupContainer={triggerNode => triggerNode.parentNode}\n" ], "file_path": "superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSqlTabContent.jsx", "type": "add", "edit_start_line_idx": 118 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M2 12C2 6.48 6.48 2 12 2C17.52 2 22 6.48 22 12C22 17.52 17.52 22 12 22C6.48 22 2 17.52 2 12ZM20 12C20 16.4183 16.4183 20 12 20C7.58172 20 4 16.4183 4 12C4 7.58172 7.58172 4 12 4C16.4183 4 20 7.58172 20 12Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/circle.svg
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017872778698801994, 0.000176625486346893, 0.00017320358892902732, 0.00017794506857171655, 0.0000024406519969488727 ]
{ "id": 4, "code_window": [ " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('Saved metric')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-saved\" {...savedSelectProps}>\n", " {Array.isArray(savedMetricsOptions) &&\n", " savedMetricsOptions.map(savedMetric => (\n", " <Select.Option\n", " value={savedMetric.id}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...savedSelectProps}\n", " name=\"select-saved\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 356 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import Tabs from 'src/common/components/Tabs'; import Button from 'src/components/Button'; import { Select } from 'src/common/components/Select'; import { styled, t } from '@superset-ui/core'; import { ColumnOption } from '@superset-ui/chart-controls'; import FormLabel from 'src/components/FormLabel'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import { noOp } from 'src/utils/common'; import { AGGREGATES_OPTIONS } from 'src/explore/constants'; import columnType from 'src/explore/propTypes/columnType'; import savedMetricType from './savedMetricType'; import AdhocMetric, { EXPRESSION_TYPES } from './AdhocMetric'; const propTypes = { adhocMetric: PropTypes.instanceOf(AdhocMetric).isRequired, onChange: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onResize: PropTypes.func.isRequired, getCurrentTab: PropTypes.func, getCurrentLabel: PropTypes.func, columns: PropTypes.arrayOf(columnType), savedMetricsOptions: PropTypes.arrayOf(savedMetricType), savedMetric: savedMetricType, datasourceType: PropTypes.string, }; const defaultProps = { columns: [], getCurrentTab: noOp, }; const ResizeIcon = styled.i` margin-left: ${({ theme }) => theme.gridUnit * 2}px; `; const ColumnOptionStyle = styled.span` .option-label { display: inline; } `; export const SAVED_TAB_KEY = 'SAVED'; const startingWidth = 320; const startingHeight = 240; export default class AdhocMetricEditPopover extends React.PureComponent { // "Saved" is a default tab unless there are no saved metrics for dataset defaultActiveTabKey = (this.props.savedMetric.metric_name || this.props.adhocMetric.isNew) && Array.isArray(this.props.savedMetricsOptions) && this.props.savedMetricsOptions.length > 0 ? SAVED_TAB_KEY : this.props.adhocMetric.expressionType; constructor(props) { super(props); this.onSave = this.onSave.bind(this); this.onResetStateAndClose = this.onResetStateAndClose.bind(this); this.onColumnChange = this.onColumnChange.bind(this); this.onAggregateChange = this.onAggregateChange.bind(this); this.onSavedMetricChange = this.onSavedMetricChange.bind(this); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onDragDown = this.onDragDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTabChange = this.onTabChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.refreshAceEditor = this.refreshAceEditor.bind(this); this.state = { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, width: startingWidth, height: startingHeight, }; document.addEventListener('mouseup', this.onMouseUp); } componentDidMount() { this.props.getCurrentTab(this.defaultActiveTabKey); } componentDidUpdate(prevProps, prevState) { if ( prevState.adhocMetric?.sqlExpression !== this.state.adhocMetric?.sqlExpression || prevState.adhocMetric?.aggregate !== this.state.adhocMetric?.aggregate || prevState.adhocMetric?.column?.column_name !== this.state.adhocMetric?.column?.column_name || prevState.savedMetric?.metric_name !== this.state.savedMetric?.metric_name ) { this.props.getCurrentLabel({ savedMetricLabel: this.state.savedMetric?.verbose_name || this.state.savedMetric?.metric_name, adhocMetricLabel: this.state.adhocMetric?.getDefaultLabel(), }); } } componentWillUnmount() { document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('mousemove', this.onMouseMove); } onSave() { const { adhocMetric, savedMetric } = this.state; const metric = savedMetric?.metric_name ? savedMetric : adhocMetric; const oldMetric = this.props.savedMetric?.metric_name ? this.props.savedMetric : this.props.adhocMetric; this.props.onChange( { ...metric, }, oldMetric, ); this.props.onClose(); } onResetStateAndClose() { this.setState( { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, }, this.props.onClose, ); } onColumnChange(columnId) { const column = this.props.columns.find(column => column.id === columnId); this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ column, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onAggregateChange(aggregate) { // we construct this object explicitly to overwrite the value in the case aggregate is null this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ aggregate, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onSavedMetricChange(savedMetricId) { const savedMetric = this.props.savedMetricsOptions.find( metric => metric.id === savedMetricId, ); this.setState(prevState => ({ savedMetric, adhocMetric: prevState.adhocMetric.duplicateWith({ column: undefined, aggregate: undefined, sqlExpression: undefined, expressionType: EXPRESSION_TYPES.SIMPLE, }), })); } onSqlExpressionChange(sqlExpression) { this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), savedMetric: undefined, })); } onDragDown(e) { this.dragStartX = e.clientX; this.dragStartY = e.clientY; this.dragStartWidth = this.state.width; this.dragStartHeight = this.state.height; document.addEventListener('mousemove', this.onMouseMove); } onMouseMove(e) { this.props.onResize(); this.setState({ width: Math.max( this.dragStartWidth + (e.clientX - this.dragStartX), startingWidth, ), height: Math.max( this.dragStartHeight + (e.clientY - this.dragStartY) * 2, startingHeight, ), }); } onMouseUp() { document.removeEventListener('mousemove', this.onMouseMove); } onTabChange(tab) { this.refreshAceEditor(); this.props.getCurrentTab(tab); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } refreshAceEditor() { setTimeout(() => { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } }, 0); } renderColumnOption(option) { const column = { ...option }; if (column.metric_name && !column.verbose_name) { column.verbose_name = column.metric_name; } return ( <ColumnOptionStyle> <ColumnOption column={column} showType /> </ColumnOptionStyle> ); } render() { const { adhocMetric: propsAdhocMetric, savedMetric: propsSavedMetric, columns, savedMetricsOptions, onChange, onClose, onResize, datasourceType, ...popoverProps } = this.props; const { adhocMetric, savedMetric } = this.state; const keywords = sqlKeywords.concat( columns.map(column => ({ name: column.column_name, value: column.column_name, score: 50, meta: 'column', })), ); const columnValue = (adhocMetric.column && adhocMetric.column.column_name) || adhocMetric.inferSqlExpressionColumn(); // autofocus on column if there's no value in column; otherwise autofocus on aggregate const columnSelectProps = { placeholder: t('%s column(s)', columns.length), value: columnValue, onChange: this.onColumnChange, allowClear: true, showSearch: true, autoFocus: !columnValue, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; const aggregateSelectProps = { placeholder: t('%s aggregates(s)', AGGREGATES_OPTIONS.length), value: adhocMetric.aggregate || adhocMetric.inferSqlExpressionAggregate(), onChange: this.onAggregateChange, allowClear: true, autoFocus: !!columnValue, showSearch: true, }; const savedSelectProps = { placeholder: t('%s saved metric(s)', savedMetricsOptions?.length ?? 0), value: savedMetric?.verbose_name || savedMetric?.metric_name, onChange: this.onSavedMetricChange, allowClear: true, showSearch: true, autoFocus: true, filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, }; if (this.props.datasourceType === 'druid') { aggregateSelectProps.options = aggregateSelectProps.options.filter( aggregate => aggregate !== 'AVG', ); } const stateIsValid = adhocMetric.isValid() || savedMetric?.metric_name; const hasUnsavedChanges = !adhocMetric.equals(propsAdhocMetric) || (!( typeof savedMetric?.metric_name === 'undefined' && typeof propsSavedMetric?.metric_name === 'undefined' ) && savedMetric?.metric_name !== propsSavedMetric?.metric_name); return ( <div id="metrics-edit-popover" data-test="metrics-edit-popover" {...popoverProps} > <Tabs id="adhoc-metric-edit-tabs" data-test="adhoc-metric-edit-tabs" defaultActiveKey={this.defaultActiveTabKey} className="adhoc-metric-edit-tabs" style={{ height: this.state.height, width: this.state.width }} onChange={this.onTabChange} allowOverflow > <Tabs.TabPane key={SAVED_TAB_KEY} tab={t('Saved')}> <FormGroup> <FormLabel> <strong>{t('Saved metric')}</strong> </FormLabel> <Select name="select-saved" {...savedSelectProps}> {Array.isArray(savedMetricsOptions) && savedMetricsOptions.map(savedMetric => ( <Select.Option value={savedMetric.id} filterBy={ savedMetric.verbose_name || savedMetric.metric_name } key={savedMetric.id} > {this.renderColumnOption(savedMetric)} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}> <FormGroup> <FormLabel> <strong>{t('column')}</strong> </FormLabel> <Select name="select-column" {...columnSelectProps}> {columns.map(column => ( <Select.Option value={column.id} filterBy={column.verbose_name || column.column_name} key={column.id} > {this.renderColumnOption(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <FormLabel> <strong>{t('aggregate')}</strong> </FormLabel> <Select name="select-aggregate" {...aggregateSelectProps}> {AGGREGATES_OPTIONS.map(option => ( <Select.Option value={option} key={option}> {option} </Select.Option> ))} </Select> </FormGroup> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SQL} tab={t('Custom SQL')} data-test="adhoc-metric-edit-tab#custom" > {this.props.datasourceType !== 'druid' ? ( <FormGroup data-test="sql-editor"> <SQLEditor showLoadingForImport ref={this.handleAceEditorRef} keywords={keywords} height={`${this.state.height - 80}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={ adhocMetric.sqlExpression || adhocMetric.translateToSql() } editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="adhoc-filter-sql-editor" wrapEnabled /> </FormGroup> ) : ( <div className="custom-sql-disabled-message"> Custom SQL Metrics are not available on druid datasources </div> )} </Tabs.TabPane> </Tabs> <div> <Button buttonSize="small" onClick={this.onResetStateAndClose} data-test="AdhocMetricEdit#cancel" cta > {t('Close')} </Button> <Button disabled={!stateIsValid} buttonStyle={ hasUnsavedChanges && stateIsValid ? 'primary' : 'default' } buttonSize="small" data-test="AdhocMetricEdit#save" onClick={this.onSave} cta > {t('Save')} </Button> <ResizeIcon role="button" aria-label="Resize" tabIndex={0} onMouseDown={this.onDragDown} className="fa fa-expand edit-popover-resize text-muted" /> </div> </div> ); } } AdhocMetricEditPopover.propTypes = propTypes; AdhocMetricEditPopover.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.9975270628929138, 0.0442853718996048, 0.00016203236009459943, 0.00025923410430550575, 0.19971488416194916 ]
{ "id": 4, "code_window": [ " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('Saved metric')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-saved\" {...savedSelectProps}>\n", " {Array.isArray(savedMetricsOptions) &&\n", " savedMetricsOptions.map(savedMetric => (\n", " <Select.Option\n", " value={savedMetric.id}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...savedSelectProps}\n", " name=\"select-saved\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 356 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import logging from typing import Optional from flask_appbuilder.models.sqla import Model from flask_appbuilder.security.sqla.models import User from sqlalchemy.exc import SQLAlchemyError from superset.commands.base import BaseCommand from superset.connectors.sqla.models import SqlaTable from superset.dao.exceptions import DAODeleteFailedError from superset.datasets.commands.exceptions import ( DatasetDeleteFailedError, DatasetForbiddenError, DatasetNotFoundError, ) from superset.datasets.dao import DatasetDAO from superset.exceptions import SupersetSecurityException from superset.extensions import db, security_manager from superset.views.base import check_ownership logger = logging.getLogger(__name__) class DeleteDatasetCommand(BaseCommand): def __init__(self, user: User, model_id: int): self._actor = user self._model_id = model_id self._model: Optional[SqlaTable] = None def run(self) -> Model: self.validate() try: dataset = DatasetDAO.delete(self._model, commit=False) view_menu = ( security_manager.find_view_menu(self._model.get_perm()) if self._model else None ) if view_menu: permission_views = ( db.session.query(security_manager.permissionview_model) .filter_by(view_menu=view_menu) .all() ) for permission_view in permission_views: db.session.delete(permission_view) if view_menu: db.session.delete(view_menu) else: if not view_menu: logger.error( "Could not find the data access permission for the dataset" ) db.session.commit() except (SQLAlchemyError, DAODeleteFailedError) as ex: logger.exception(ex) db.session.rollback() raise DatasetDeleteFailedError() return dataset def validate(self) -> None: # Validate/populate model exists self._model = DatasetDAO.find_by_id(self._model_id) if not self._model: raise DatasetNotFoundError() # Check ownership try: check_ownership(self._model) except SupersetSecurityException: raise DatasetForbiddenError()
superset/datasets/commands/delete.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00018356267537456006, 0.00017605476023163646, 0.0001697873667581007, 0.000174618253367953, 0.00000469159249405493 ]
{ "id": 4, "code_window": [ " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('Saved metric')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-saved\" {...savedSelectProps}>\n", " {Array.isArray(savedMetricsOptions) &&\n", " savedMetricsOptions.map(savedMetric => (\n", " <Select.Option\n", " value={savedMetric.id}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...savedSelectProps}\n", " name=\"select-saved\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 356 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """a collection of model-related helper classes and functions""" import json import logging import re import uuid from datetime import datetime, timedelta from json.decoder import JSONDecodeError from typing import Any, Dict, List, Optional, Set, Union import humanize import pandas as pd import pytz import sqlalchemy as sa import yaml from flask import escape, g, Markup from flask_appbuilder.models.decorators import renders from flask_appbuilder.models.mixins import AuditMixin from flask_appbuilder.security.sqla.models import User from sqlalchemy import and_, or_, UniqueConstraint from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import Mapper, Session from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils import UUIDType from superset.utils.core import QueryStatus logger = logging.getLogger(__name__) def json_to_dict(json_str: str) -> Dict[Any, Any]: if json_str: val = re.sub(",[ \t\r\n]+}", "}", json_str) val = re.sub(",[ \t\r\n]+\\]", "]", val) return json.loads(val) return {} def convert_uuids(obj: Any) -> Any: """ Convert UUID objects to str so we can use yaml.safe_dump """ if isinstance(obj, uuid.UUID): return str(obj) if isinstance(obj, list): return [convert_uuids(el) for el in obj] if isinstance(obj, dict): return {k: convert_uuids(v) for k, v in obj.items()} return obj class ImportExportMixin: uuid = sa.Column( UUIDType(binary=True), primary_key=False, unique=True, default=uuid.uuid4 ) export_parent: Optional[str] = None # The name of the attribute # with the SQL Alchemy back reference export_children: List[str] = [] # List of (str) names of attributes # with the SQL Alchemy forward references export_fields: List[str] = [] # The names of the attributes # that are available for import and export extra_import_fields: List[str] = [] # Additional fields that should be imported, # even though they were not exported __mapper__: Mapper @classmethod def _unique_constrains(cls) -> List[Set[str]]: """Get all (single column and multi column) unique constraints""" unique = [ {c.name for c in u.columns} for u in cls.__table_args__ # type: ignore if isinstance(u, UniqueConstraint) ] unique.extend( {c.name} for c in cls.__table__.columns if c.unique # type: ignore ) return unique @classmethod def parent_foreign_key_mappings(cls) -> Dict[str, str]: """Get a mapping of foreign name to the local name of foreign keys""" parent_rel = cls.__mapper__.relationships.get(cls.export_parent) if parent_rel: return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs} return {} @classmethod def export_schema( cls, recursive: bool = True, include_parent_ref: bool = False ) -> Dict[str, Any]: """Export schema as a dictionary""" parent_excludes = set() if not include_parent_ref: parent_ref = cls.__mapper__.relationships.get(cls.export_parent) if parent_ref: parent_excludes = {column.name for column in parent_ref.local_columns} def formatter(column: sa.Column) -> str: return ( "{0} Default ({1})".format(str(column.type), column.default.arg) if column.default else str(column.type) ) schema: Dict[str, Any] = { column.name: formatter(column) for column in cls.__table__.columns # type: ignore if (column.name in cls.export_fields and column.name not in parent_excludes) } if recursive: for column in cls.export_children: child_class = cls.__mapper__.relationships[column].argument.class_ schema[column] = [ child_class.export_schema( recursive=recursive, include_parent_ref=include_parent_ref ) ] return schema @classmethod def import_from_dict( # pylint: disable=too-many-arguments,too-many-branches,too-many-locals cls, session: Session, dict_rep: Dict[Any, Any], parent: Optional[Any] = None, recursive: bool = True, sync: Optional[List[str]] = None, ) -> Any: """Import obj from a dictionary""" if sync is None: sync = [] parent_refs = cls.parent_foreign_key_mappings() export_fields = ( set(cls.export_fields) | set(cls.extra_import_fields) | set(parent_refs.keys()) | {"uuid"} ) new_children = {c: dict_rep[c] for c in cls.export_children if c in dict_rep} unique_constrains = cls._unique_constrains() filters = [] # Using these filters to check if obj already exists # Remove fields that should not get imported for k in list(dict_rep): if k not in export_fields and k not in parent_refs: del dict_rep[k] if not parent: if cls.export_parent: for prnt in parent_refs.keys(): if prnt not in dict_rep: raise RuntimeError( "{0}: Missing field {1}".format(cls.__name__, prnt) ) else: # Set foreign keys to parent obj for k, v in parent_refs.items(): dict_rep[k] = getattr(parent, v) # Add filter for parent obj filters.extend([getattr(cls, k) == dict_rep.get(k) for k in parent_refs.keys()]) # Add filter for unique constraints ucs = [ and_( *[ getattr(cls, k) == dict_rep.get(k) for k in cs if dict_rep.get(k) is not None ] ) for cs in unique_constrains ] filters.append(or_(*ucs)) # Check if object already exists in DB, break if more than one is found try: obj_query = session.query(cls).filter(and_(*filters)) obj = obj_query.one_or_none() except MultipleResultsFound as ex: logger.error( "Error importing %s \n %s \n %s", cls.__name__, str(obj_query), yaml.safe_dump(dict_rep), ) raise ex if not obj: is_new_obj = True # Create new DB object obj = cls(**dict_rep) # type: ignore logger.info("Importing new %s %s", obj.__tablename__, str(obj)) if cls.export_parent and parent: setattr(obj, cls.export_parent, parent) session.add(obj) else: is_new_obj = False logger.info("Updating %s %s", obj.__tablename__, str(obj)) # Update columns for k, v in dict_rep.items(): setattr(obj, k, v) # Recursively create children if recursive: for child in cls.export_children: child_class = cls.__mapper__.relationships[child].argument.class_ added = [] for c_obj in new_children.get(child, []): added.append( child_class.import_from_dict( session=session, dict_rep=c_obj, parent=obj, sync=sync ) ) # If children should get synced, delete the ones that did not # get updated. if child in sync and not is_new_obj: back_refs = child_class.parent_foreign_key_mappings() delete_filters = [ getattr(child_class, k) == getattr(obj, back_refs.get(k)) for k in back_refs.keys() ] to_delete = set( session.query(child_class).filter(and_(*delete_filters)) ).difference(set(added)) for o in to_delete: logger.info("Deleting %s %s", child, str(obj)) session.delete(o) return obj def export_to_dict( self, recursive: bool = True, include_parent_ref: bool = False, include_defaults: bool = False, export_uuids: bool = False, ) -> Dict[Any, Any]: """Export obj to dictionary""" export_fields = set(self.export_fields) if export_uuids: export_fields.add("uuid") if "id" in export_fields: export_fields.remove("id") cls = self.__class__ parent_excludes = set() if recursive and not include_parent_ref: parent_ref = cls.__mapper__.relationships.get(cls.export_parent) if parent_ref: parent_excludes = {c.name for c in parent_ref.local_columns} dict_rep = { c.name: getattr(self, c.name) for c in cls.__table__.columns # type: ignore if ( c.name in export_fields and c.name not in parent_excludes and ( include_defaults or ( getattr(self, c.name) is not None and (not c.default or getattr(self, c.name) != c.default.arg) ) ) ) } # sort according to export_fields using DSU (decorate, sort, undecorate) order = {field: i for i, field in enumerate(self.export_fields)} decorated_keys = [(order.get(k, len(order)), k) for k in dict_rep] decorated_keys.sort() dict_rep = {k: dict_rep[k] for _, k in decorated_keys} if recursive: for cld in self.export_children: # sorting to make lists of children stable dict_rep[cld] = sorted( [ child.export_to_dict( recursive=recursive, include_parent_ref=include_parent_ref, include_defaults=include_defaults, ) for child in getattr(self, cld) ], key=lambda k: sorted(str(k.items())), ) return convert_uuids(dict_rep) def override(self, obj: Any) -> None: """Overrides the plain fields of the dashboard.""" for field in obj.__class__.export_fields: setattr(self, field, getattr(obj, field)) def copy(self) -> Any: """Creates a copy of the dashboard without relationships.""" new_obj = self.__class__() new_obj.override(self) return new_obj def alter_params(self, **kwargs: Any) -> None: params = self.params_dict params.update(kwargs) self.params = json.dumps(params) def remove_params(self, param_to_remove: str) -> None: params = self.params_dict params.pop(param_to_remove, None) self.params = json.dumps(params) def reset_ownership(self) -> None: """ object will belong to the user the current user """ # make sure the object doesn't have relations to a user # it will be filled by appbuilder on save self.created_by = None self.changed_by = None # flask global context might not exist (in cli or tests for example) self.owners = [] if g and hasattr(g, "user"): self.owners = [g.user] @property def params_dict(self) -> Dict[Any, Any]: return json_to_dict(self.params) @property def template_params_dict(self) -> Dict[Any, Any]: return json_to_dict(self.template_params) # type: ignore def _user_link(user: User) -> Union[Markup, str]: if not user: return "" url = "/superset/profile/{}/".format(user.username) return Markup('<a href="{}">{}</a>'.format(url, escape(user) or "")) class AuditMixinNullable(AuditMixin): """Altering the AuditMixin to use nullable fields Allows creating objects programmatically outside of CRUD """ created_on = sa.Column(sa.DateTime, default=datetime.now, nullable=True) changed_on = sa.Column( sa.DateTime, default=datetime.now, onupdate=datetime.now, nullable=True ) @declared_attr def created_by_fk(self) -> sa.Column: return sa.Column( sa.Integer, sa.ForeignKey("ab_user.id"), default=self.get_user_id, nullable=True, ) @declared_attr def changed_by_fk(self) -> sa.Column: return sa.Column( sa.Integer, sa.ForeignKey("ab_user.id"), default=self.get_user_id, onupdate=self.get_user_id, nullable=True, ) @property def changed_by_name(self) -> str: if self.changed_by: return escape("{}".format(self.changed_by)) return "" @renders("created_by") def creator(self) -> Union[Markup, str]: return _user_link(self.created_by) @property def changed_by_(self) -> Union[Markup, str]: return _user_link(self.changed_by) @renders("changed_on") def changed_on_(self) -> Markup: return Markup(f'<span class="no-wrap">{self.changed_on}</span>') @renders("changed_on") def changed_on_delta_humanized(self) -> str: return self.changed_on_humanized @renders("changed_on") def changed_on_utc(self) -> str: # Convert naive datetime to UTC return self.changed_on.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S.%f%z") @property def changed_on_humanized(self) -> str: return humanize.naturaltime(datetime.now() - self.changed_on) @renders("changed_on") def modified(self) -> Markup: return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>') class QueryResult: # pylint: disable=too-few-public-methods """Object returned by the query interface""" def __init__( # pylint: disable=too-many-arguments self, df: pd.DataFrame, query: str, duration: timedelta, status: str = QueryStatus.SUCCESS, error_message: Optional[str] = None, errors: Optional[List[Dict[str, Any]]] = None, ) -> None: self.df = df self.query = query self.duration = duration self.status = status self.error_message = error_message self.errors = errors or [] class ExtraJSONMixin: """Mixin to add an `extra` column (JSON) and utility methods""" extra_json = sa.Column(sa.Text, default="{}") @property def extra(self) -> Dict[str, Any]: try: return json.loads(self.extra_json) except (TypeError, JSONDecodeError) as exc: logger.error( "Unable to load an extra json: %r. Leaving empty.", exc, exc_info=True ) return {} def set_extra_json(self, extras: Dict[str, Any]) -> None: self.extra_json = json.dumps(extras) def set_extra_json_key(self, key: str, value: Any) -> None: extra = self.extra extra[key] = value self.extra_json = json.dumps(extra)
superset/models/helpers.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0008988432819023728, 0.00019235727086197585, 0.00016173011681530625, 0.00016919698100537062, 0.00011259849270572886 ]
{ "id": 4, "code_window": [ " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('Saved metric')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-saved\" {...savedSelectProps}>\n", " {Array.isArray(savedMetricsOptions) &&\n", " savedMetricsOptions.map(savedMetric => (\n", " <Select.Option\n", " value={savedMetric.id}\n", " filterBy={\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...savedSelectProps}\n", " name=\"select-saved\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 356 }
{# Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. #} {% extends 'appbuilder/general/widgets/roles/list.html' %} {% block begin_content scoped %} <div class="table-responsive"> <table class="table table-hover"> {% endblock %}
superset/templates/superset/fab_overrides/list_role.html
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00018273023306392133, 0.00017610179202165455, 0.00016824575141072273, 0.00017732937703840435, 0.000005976637112325989 ]
{ "id": 5, "code_window": [ " <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}>\n", " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('column')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-column\" {...columnSelectProps}>\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...columnSelectProps}\n", " name=\"select-column\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 377 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import { Select } from 'src/common/components/Select'; import { Input } from 'src/common/components'; import { t, SupersetClient, styled } from '@superset-ui/core'; import adhocMetricType from 'src/explore/components/controls/MetricControl/adhocMetricType'; import columnType from 'src/explore/propTypes/columnType'; import { OPERATORS, OPERATORS_OPTIONS, TABLE_ONLY_OPERATORS, DRUID_ONLY_OPERATORS, HAVING_OPERATORS, MULTI_OPERATORS, CUSTOM_OPERATORS, DISABLE_INPUT_OPERATORS, } from 'src/explore/constants'; import FilterDefinitionOption from 'src/explore/components/controls/MetricControl/FilterDefinitionOption'; import AdhocFilter, { EXPRESSION_TYPES, CLAUSES } from './AdhocFilter'; const SelectWithLabel = styled(Select)` .ant-select-selector::after { content: '${({ labelText }) => labelText || '\\A0'}'; display: inline-block; white-space: nowrap; color: ${({ theme }) => theme.colors.grayscale.light1}; width: max-content; } `; const propTypes = { adhocFilter: PropTypes.instanceOf(AdhocFilter).isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf( PropTypes.oneOfType([ columnType, PropTypes.shape({ saved_metric_name: PropTypes.string.isRequired }), adhocMetricType, ]), ).isRequired, onHeightChange: PropTypes.func.isRequired, datasource: PropTypes.object, partitionColumn: PropTypes.string, popoverRef: PropTypes.object, }; const defaultProps = { datasource: {}, }; function translateOperator(operator) { if (operator === OPERATORS['==']) { return 'equals'; } if (operator === OPERATORS['!=']) { return 'not equal to'; } if (operator === OPERATORS.LIKE) { return 'LIKE'; } if (operator === OPERATORS['LATEST PARTITION']) { return 'use latest_partition template'; } return operator; } export default class AdhocFilterEditPopoverSimpleTabContent extends React.Component { constructor(props) { super(props); this.onSubjectChange = this.onSubjectChange.bind(this); this.onOperatorChange = this.onOperatorChange.bind(this); this.onComparatorChange = this.onComparatorChange.bind(this); this.onInputComparatorChange = this.onInputComparatorChange.bind(this); this.isOperatorRelevant = this.isOperatorRelevant.bind(this); this.refreshComparatorSuggestions = this.refreshComparatorSuggestions.bind( this, ); this.state = { suggestions: [], abortActiveRequest: null, }; this.selectProps = { name: 'select-column', showSearch: true, }; } UNSAFE_componentWillMount() { this.refreshComparatorSuggestions(); } componentDidUpdate(prevProps) { if (prevProps.adhocFilter.subject !== this.props.adhocFilter.subject) { this.refreshComparatorSuggestions(); } } onSubjectChange(id) { const option = this.props.options.find( option => option.id === id || option.optionName === id, ); let subject; let clause; // infer the new clause based on what subject was selected. if (option && option.column_name) { subject = option.column_name; clause = CLAUSES.WHERE; } else if (option && (option.saved_metric_name || option.label)) { subject = option.saved_metric_name || option.label; clause = CLAUSES.HAVING; } const { operator } = this.props.adhocFilter; this.props.onChange( this.props.adhocFilter.duplicateWith({ subject, clause, operator: operator && this.isOperatorRelevant(operator, subject) ? operator : null, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } onOperatorChange(operator) { const currentComparator = this.props.adhocFilter.comparator; let newComparator; // convert between list of comparators and individual comparators // (e.g. `in ('North America', 'Africa')` to `== 'North America'`) if (MULTI_OPERATORS.has(operator)) { newComparator = Array.isArray(currentComparator) ? currentComparator : [currentComparator].filter(element => element); } else { newComparator = Array.isArray(currentComparator) ? currentComparator[0] : currentComparator; } if (operator && CUSTOM_OPERATORS.has(operator)) { this.props.onChange( this.props.adhocFilter.duplicateWith({ subject: this.props.adhocFilter.subject, clause: CLAUSES.WHERE, operator, expressionType: EXPRESSION_TYPES.SQL, datasource: this.props.datasource, }), ); } else { this.props.onChange( this.props.adhocFilter.duplicateWith({ operator, comparator: newComparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } } onInputComparatorChange(event) { this.onComparatorChange(event.target.value); } onComparatorChange(comparator) { this.props.onChange( this.props.adhocFilter.duplicateWith({ comparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } refreshComparatorSuggestions() { const { datasource } = this.props; const col = this.props.adhocFilter.subject; const having = this.props.adhocFilter.clause === CLAUSES.HAVING; if (col && datasource && datasource.filter_select && !having) { if (this.state.abortActiveRequest) { this.state.abortActiveRequest(); } const controller = new AbortController(); const { signal } = controller; this.setState({ abortActiveRequest: controller.abort, loading: true }); SupersetClient.get({ signal, endpoint: `/superset/filter/${datasource.type}/${datasource.id}/${col}/`, }) .then(({ json }) => { this.setState(() => ({ suggestions: json, abortActiveRequest: null, loading: false, })); }) .catch(() => { this.setState(() => ({ suggestions: [], abortActiveRequest: null, loading: false, })); }); } } isOperatorRelevant(operator, subject) { if (operator && CUSTOM_OPERATORS.has(operator)) { const { partitionColumn } = this.props; return partitionColumn && subject && subject === partitionColumn; } return !( (this.props.datasource.type === 'druid' && TABLE_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.datasource.type === 'table' && DRUID_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.adhocFilter.clause === CLAUSES.HAVING && HAVING_OPERATORS.indexOf(operator) === -1) ); } focusComparator(ref, shouldFocus) { if (ref && shouldFocus) { ref.focus(); } } optionsRemaining() { const { suggestions } = this.state; const { comparator } = this.props.adhocFilter; // if select is multi/value is array, we show the options not selected const valuesFromSuggestionsLength = Array.isArray(comparator) ? comparator.filter(v => suggestions.includes(v)).length : 0; return suggestions?.length - valuesFromSuggestionsLength ?? 0; } createSuggestionsPlaceholder() { const optionsRemaining = this.optionsRemaining(); const placeholder = t('%s option(s)', optionsRemaining); return optionsRemaining ? placeholder : ''; } renderSubjectOptionLabel(option) { return <FilterDefinitionOption option={option} />; } render() { const { adhocFilter, options, datasource } = this.props; let columns = options; const { subject, operator, comparator } = adhocFilter; const subjectSelectProps = { value: subject ?? undefined, onChange: this.onSubjectChange, notFoundContent: t( 'No such column found. To filter on a metric, try the Custom SQL tab.', ), filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !subject, }; if (datasource.type === 'druid') { subjectSelectProps.placeholder = t( '%s column(s) and metric(s)', columns.length, ); } else { // we cannot support simple ad-hoc filters for metrics because we don't know what type // the value should be cast to (without knowing the output type of the aggregate, which // becomes a rather complicated problem) subjectSelectProps.placeholder = adhocFilter.clause === CLAUSES.WHERE ? t('%s column(s)', columns.length) : t('To filter on a metric, use Custom SQL tab.'); columns = options.filter(option => option.column_name); } const operatorSelectProps = { placeholder: t( '%s operator(s)', OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject)) .length, ), // like AGGREGTES_OPTIONS, operator options are string value: operator, onChange: this.onOperatorChange, filterOption: (input, option) => option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !!subjectSelectProps.value && !operator, }; const focusComparator = !!subjectSelectProps.value && !!operatorSelectProps.value; const comparatorSelectProps = { allowClear: true, showSearch: true, mode: MULTI_OPERATORS.has(operator) && 'tags', tokenSeparators: [',', '\n', '\t', ';'], loading: this.state.loading, value: comparator, onChange: this.onComparatorChange, notFoundContent: t('Type a value here'), disabled: DISABLE_INPUT_OPERATORS.includes(operator), placeholder: this.createSuggestionsPlaceholder(), labelText: comparator?.length > 0 && this.createSuggestionsPlaceholder(), autoFocus: focusComparator, }; return ( <> <FormGroup className="adhoc-filter-simple-column-dropdown"> <Select {...this.selectProps} {...subjectSelectProps} name="filter-column" > {columns.map(column => ( <Select.Option value={column.id || column.optionName} filterBy={ column.saved_metric_name || column.column_name || column.label } key={column.id || column.optionName} > {this.renderSubjectOptionLabel(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <Select {...this.selectProps} {...operatorSelectProps} name="filter-operator" > {OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject), ).map(option => ( <Select.Option value={option} key={option}> {translateOperator(option)} </Select.Option> ))} </Select> </FormGroup> <FormGroup data-test="adhoc-filter-simple-value"> {MULTI_OPERATORS.has(operator) || this.state.suggestions.length > 0 ? ( <SelectWithLabel name="filter-value" {...comparatorSelectProps}> {this.state.suggestions.map(suggestion => ( <Select.Option value={suggestion} key={suggestion}> {suggestion} </Select.Option> ))} </SelectWithLabel> ) : ( <Input name="filter-value" ref={ref => this.focusComparator(ref, focusComparator)} onChange={this.onInputComparatorChange} value={comparator} placeholder={t('Filter value (case sensitive)')} disabled={DISABLE_INPUT_OPERATORS.includes(operator)} /> )} </FormGroup> </> ); } } AdhocFilterEditPopoverSimpleTabContent.propTypes = propTypes; AdhocFilterEditPopoverSimpleTabContent.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.9793086647987366, 0.027134642004966736, 0.0001625207078177482, 0.0001768426736816764, 0.15298700332641602 ]
{ "id": 5, "code_window": [ " <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}>\n", " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('column')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-column\" {...columnSelectProps}>\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...columnSelectProps}\n", " name=\"select-column\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 377 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import json import pandas as pd import polyline from sqlalchemy import String, Text from superset import db from superset.utils.core import get_example_database from .helpers import get_example_data, TBL def load_bart_lines(only_metadata: bool = False, force: bool = False) -> None: tbl_name = "bart_lines" database = get_example_database() table_exists = database.has_table_by_name(tbl_name) if not only_metadata and (not table_exists or force): content = get_example_data("bart-lines.json.gz") df = pd.read_json(content, encoding="latin-1") df["path_json"] = df.path.map(json.dumps) df["polyline"] = df.path.map(polyline.encode) del df["path"] df.to_sql( tbl_name, database.get_sqla_engine(), if_exists="replace", chunksize=500, dtype={ "color": String(255), "name": String(255), "polyline": Text, "path_json": Text, }, index=False, ) print("Creating table {} reference".format(tbl_name)) tbl = db.session.query(TBL).filter_by(table_name=tbl_name).first() if not tbl: tbl = TBL(table_name=tbl_name) tbl.description = "BART lines" tbl.database = database db.session.merge(tbl) db.session.commit() tbl.fetch_metadata()
superset/examples/bart_lines.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0001789523521438241, 0.0001735887344693765, 0.00016774404502939433, 0.00017338682664558291, 0.000003908505732397316 ]
{ "id": 5, "code_window": [ " <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}>\n", " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('column')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-column\" {...columnSelectProps}>\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...columnSelectProps}\n", " name=\"select-column\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 377 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import logging from io import IOBase from typing import cast, Optional, Union from flask import current_app from retry.api import retry from slack import WebClient from slack.errors import SlackApiError from slack.web.slack_response import SlackResponse # Globals logger = logging.getLogger("tasks.slack_util") @retry(SlackApiError, delay=10, backoff=2, tries=5) def deliver_slack_msg( slack_channel: str, subject: str, body: str, file: Optional[Union[str, IOBase, bytes]], ) -> None: config = current_app.config client = WebClient(token=config["SLACK_API_TOKEN"], proxy=config["SLACK_PROXY"]) # files_upload returns SlackResponse as we run it in sync mode. if file: response = cast( SlackResponse, client.files_upload( channels=slack_channel, file=file, initial_comment=body, title=subject ), ) assert response["file"], str(response) # the uploaded file else: response = cast( SlackResponse, client.chat_postMessage(channel=slack_channel, text=body), ) assert response["message"]["text"], str(response) logger.info("Sent the report to the slack %s", slack_channel)
superset/tasks/slack_util.py
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017895217752084136, 0.00017485964053776115, 0.00017195413238368928, 0.00017472260515205562, 0.0000024326150196429808 ]
{ "id": 5, "code_window": [ " <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={t('Simple')}>\n", " <FormGroup>\n", " <FormLabel>\n", " <strong>{t('column')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-column\" {...columnSelectProps}>\n", " {columns.map(column => (\n", " <Select.Option\n", " value={column.id}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...columnSelectProps}\n", " name=\"select-column\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 377 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import moment, { Moment } from 'moment'; import { SEPARATOR } from 'src/explore/dateFilterUtils'; import { CustomRangeDecodeType, CustomRangeType, DateTimeGrainType, DateTimeModeType, } from './types'; import { SEVEN_DAYS_AGO, MIDNIGHT, MOMENT_FORMAT } from './constants'; /** * RegExp to test a string for a full ISO 8601 Date * Does not do any sort of date validation, only checks if the string is according to the ISO 8601 spec. * YYYY-MM-DDThh:mm:ss * YYYY-MM-DDThh:mm:ssTZD * YYYY-MM-DDThh:mm:ss.sTZD * @see: https://www.w3.org/TR/NOTE-datetime */ const iso8601 = String.raw`\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:(?:[+-]\d\d:\d\d)|Z)?`; const datetimeConstant = String.raw`TODAY|NOW`; const grainValue = String.raw`[+-]?[1-9][0-9]*`; const grain = String.raw`YEAR|QUARTER|MONTH|WEEK|DAY|HOUR|MINUTE|SECOND`; const CUSTOM_RANGE_EXPRESSION = RegExp( String.raw`^DATEADD\(DATETIME\("(${iso8601}|${datetimeConstant})"\),\s(${grainValue}),\s(${grain})\)$`, 'i', ); export const ISO8601_AND_CONSTANT = RegExp( String.raw`^${iso8601}$|^${datetimeConstant}$`, 'i', ); const DATETIME_CONSTANT = ['now', 'today']; const defaultCustomRange: CustomRangeType = { sinceDatetime: SEVEN_DAYS_AGO, sinceMode: 'relative', sinceGrain: 'day', sinceGrainValue: -7, untilDatetime: MIDNIGHT, untilMode: 'specific', untilGrain: 'day', untilGrainValue: 7, anchorMode: 'now', anchorValue: 'now', }; const SPECIFIC_MODE = ['specific', 'today', 'now']; export const dttmToMoment = (dttm: string): Moment => { if (dttm === 'now') { return moment().utc().startOf('second'); } if (dttm === 'today') { return moment().utc().startOf('day'); } return moment(dttm); }; export const dttmToString = (dttm: string): string => dttmToMoment(dttm).format(MOMENT_FORMAT); export const customTimeRangeDecode = ( timeRange: string, ): CustomRangeDecodeType => { const splitDateRange = timeRange.split(SEPARATOR); if (splitDateRange.length === 2) { const [since, until] = splitDateRange; // specific : specific if (ISO8601_AND_CONSTANT.test(since) && ISO8601_AND_CONSTANT.test(until)) { const sinceMode = (DATETIME_CONSTANT.includes(since) ? since : 'specific') as DateTimeModeType; const untilMode = (DATETIME_CONSTANT.includes(until) ? until : 'specific') as DateTimeModeType; return { customRange: { ...defaultCustomRange, sinceDatetime: since, untilDatetime: until, sinceMode, untilMode, }, matchedFlag: true, }; } // relative : specific const sinceCapturedGroup = since.match(CUSTOM_RANGE_EXPRESSION); if ( sinceCapturedGroup && ISO8601_AND_CONSTANT.test(until) && since.includes(until) ) { const [dttm, grainValue, grain] = sinceCapturedGroup.slice(1); const untilMode = (DATETIME_CONSTANT.includes(until) ? until : 'specific') as DateTimeModeType; return { customRange: { ...defaultCustomRange, sinceGrain: grain as DateTimeGrainType, sinceGrainValue: parseInt(grainValue, 10), sinceDatetime: dttm, untilDatetime: dttm, sinceMode: 'relative', untilMode, }, matchedFlag: true, }; } // specific : relative const untilCapturedGroup = until.match(CUSTOM_RANGE_EXPRESSION); if ( ISO8601_AND_CONSTANT.test(since) && untilCapturedGroup && until.includes(since) ) { const [dttm, grainValue, grain] = [...untilCapturedGroup.slice(1)]; const sinceMode = (DATETIME_CONSTANT.includes(since) ? since : 'specific') as DateTimeModeType; return { customRange: { ...defaultCustomRange, untilGrain: grain as DateTimeGrainType, untilGrainValue: parseInt(grainValue, 10), sinceDatetime: dttm, untilDatetime: dttm, untilMode: 'relative', sinceMode, }, matchedFlag: true, }; } // relative : relative if (sinceCapturedGroup && untilCapturedGroup) { const [sinceDttm, sinceGrainValue, sinceGrain] = [ ...sinceCapturedGroup.slice(1), ]; const [untileDttm, untilGrainValue, untilGrain] = [ ...untilCapturedGroup.slice(1), ]; if (sinceDttm === untileDttm) { return { customRange: { ...defaultCustomRange, sinceGrain: sinceGrain as DateTimeGrainType, sinceGrainValue: parseInt(sinceGrainValue, 10), sinceDatetime: sinceDttm, untilGrain: untilGrain as DateTimeGrainType, untilGrainValue: parseInt(untilGrainValue, 10), untilDatetime: untileDttm, anchorValue: sinceDttm, sinceMode: 'relative', untilMode: 'relative', anchorMode: sinceDttm === 'now' ? 'now' : 'specific', }, matchedFlag: true, }; } } } return { customRange: defaultCustomRange, matchedFlag: false, }; }; export const customTimeRangeEncode = (customRange: CustomRangeType): string => { const { sinceDatetime, sinceMode, sinceGrain, sinceGrainValue, untilDatetime, untilMode, untilGrain, untilGrainValue, anchorValue, } = { ...customRange }; // specific : specific if (SPECIFIC_MODE.includes(sinceMode) && SPECIFIC_MODE.includes(untilMode)) { const since = sinceMode === 'specific' ? dttmToString(sinceDatetime) : sinceMode; const until = untilMode === 'specific' ? dttmToString(untilDatetime) : untilMode; return `${since} : ${until}`; } // specific : relative if (SPECIFIC_MODE.includes(sinceMode) && untilMode === 'relative') { const since = sinceMode === 'specific' ? dttmToString(sinceDatetime) : sinceMode; const until = `DATEADD(DATETIME("${since}"), ${untilGrainValue}, ${untilGrain})`; return `${since} : ${until}`; } // relative : specific if (sinceMode === 'relative' && SPECIFIC_MODE.includes(untilMode)) { const until = untilMode === 'specific' ? dttmToString(untilDatetime) : untilMode; const since = `DATEADD(DATETIME("${until}"), ${-Math.abs( sinceGrainValue, )}, ${sinceGrain})`; return `${since} : ${until}`; } // relative : relative const since = `DATEADD(DATETIME("${anchorValue}"), ${-Math.abs( sinceGrainValue, )}, ${sinceGrain})`; const until = `DATEADD(DATETIME("${anchorValue}"), ${untilGrainValue}, ${untilGrain})`; return `${since} : ${until}`; };
superset-frontend/src/explore/components/controls/DateFilterControl/utils.ts
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0005091538769192994, 0.00018642970826476812, 0.00016510384739376605, 0.00017275587015319616, 0.00006738863157806918 ]
{ "id": 6, "code_window": [ " <FormLabel>\n", " <strong>{t('aggregate')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-aggregate\" {...aggregateSelectProps}>\n", " {AGGREGATES_OPTIONS.map(option => (\n", " <Select.Option value={option} key={option}>\n", " {option}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...aggregateSelectProps}\n", " name=\"select-aggregate\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 393 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import PropTypes from 'prop-types'; import { FormGroup } from 'react-bootstrap'; import { Select } from 'src/common/components/Select'; import { Input } from 'src/common/components'; import { t, SupersetClient, styled } from '@superset-ui/core'; import adhocMetricType from 'src/explore/components/controls/MetricControl/adhocMetricType'; import columnType from 'src/explore/propTypes/columnType'; import { OPERATORS, OPERATORS_OPTIONS, TABLE_ONLY_OPERATORS, DRUID_ONLY_OPERATORS, HAVING_OPERATORS, MULTI_OPERATORS, CUSTOM_OPERATORS, DISABLE_INPUT_OPERATORS, } from 'src/explore/constants'; import FilterDefinitionOption from 'src/explore/components/controls/MetricControl/FilterDefinitionOption'; import AdhocFilter, { EXPRESSION_TYPES, CLAUSES } from './AdhocFilter'; const SelectWithLabel = styled(Select)` .ant-select-selector::after { content: '${({ labelText }) => labelText || '\\A0'}'; display: inline-block; white-space: nowrap; color: ${({ theme }) => theme.colors.grayscale.light1}; width: max-content; } `; const propTypes = { adhocFilter: PropTypes.instanceOf(AdhocFilter).isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf( PropTypes.oneOfType([ columnType, PropTypes.shape({ saved_metric_name: PropTypes.string.isRequired }), adhocMetricType, ]), ).isRequired, onHeightChange: PropTypes.func.isRequired, datasource: PropTypes.object, partitionColumn: PropTypes.string, popoverRef: PropTypes.object, }; const defaultProps = { datasource: {}, }; function translateOperator(operator) { if (operator === OPERATORS['==']) { return 'equals'; } if (operator === OPERATORS['!=']) { return 'not equal to'; } if (operator === OPERATORS.LIKE) { return 'LIKE'; } if (operator === OPERATORS['LATEST PARTITION']) { return 'use latest_partition template'; } return operator; } export default class AdhocFilterEditPopoverSimpleTabContent extends React.Component { constructor(props) { super(props); this.onSubjectChange = this.onSubjectChange.bind(this); this.onOperatorChange = this.onOperatorChange.bind(this); this.onComparatorChange = this.onComparatorChange.bind(this); this.onInputComparatorChange = this.onInputComparatorChange.bind(this); this.isOperatorRelevant = this.isOperatorRelevant.bind(this); this.refreshComparatorSuggestions = this.refreshComparatorSuggestions.bind( this, ); this.state = { suggestions: [], abortActiveRequest: null, }; this.selectProps = { name: 'select-column', showSearch: true, }; } UNSAFE_componentWillMount() { this.refreshComparatorSuggestions(); } componentDidUpdate(prevProps) { if (prevProps.adhocFilter.subject !== this.props.adhocFilter.subject) { this.refreshComparatorSuggestions(); } } onSubjectChange(id) { const option = this.props.options.find( option => option.id === id || option.optionName === id, ); let subject; let clause; // infer the new clause based on what subject was selected. if (option && option.column_name) { subject = option.column_name; clause = CLAUSES.WHERE; } else if (option && (option.saved_metric_name || option.label)) { subject = option.saved_metric_name || option.label; clause = CLAUSES.HAVING; } const { operator } = this.props.adhocFilter; this.props.onChange( this.props.adhocFilter.duplicateWith({ subject, clause, operator: operator && this.isOperatorRelevant(operator, subject) ? operator : null, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } onOperatorChange(operator) { const currentComparator = this.props.adhocFilter.comparator; let newComparator; // convert between list of comparators and individual comparators // (e.g. `in ('North America', 'Africa')` to `== 'North America'`) if (MULTI_OPERATORS.has(operator)) { newComparator = Array.isArray(currentComparator) ? currentComparator : [currentComparator].filter(element => element); } else { newComparator = Array.isArray(currentComparator) ? currentComparator[0] : currentComparator; } if (operator && CUSTOM_OPERATORS.has(operator)) { this.props.onChange( this.props.adhocFilter.duplicateWith({ subject: this.props.adhocFilter.subject, clause: CLAUSES.WHERE, operator, expressionType: EXPRESSION_TYPES.SQL, datasource: this.props.datasource, }), ); } else { this.props.onChange( this.props.adhocFilter.duplicateWith({ operator, comparator: newComparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } } onInputComparatorChange(event) { this.onComparatorChange(event.target.value); } onComparatorChange(comparator) { this.props.onChange( this.props.adhocFilter.duplicateWith({ comparator, expressionType: EXPRESSION_TYPES.SIMPLE, }), ); } refreshComparatorSuggestions() { const { datasource } = this.props; const col = this.props.adhocFilter.subject; const having = this.props.adhocFilter.clause === CLAUSES.HAVING; if (col && datasource && datasource.filter_select && !having) { if (this.state.abortActiveRequest) { this.state.abortActiveRequest(); } const controller = new AbortController(); const { signal } = controller; this.setState({ abortActiveRequest: controller.abort, loading: true }); SupersetClient.get({ signal, endpoint: `/superset/filter/${datasource.type}/${datasource.id}/${col}/`, }) .then(({ json }) => { this.setState(() => ({ suggestions: json, abortActiveRequest: null, loading: false, })); }) .catch(() => { this.setState(() => ({ suggestions: [], abortActiveRequest: null, loading: false, })); }); } } isOperatorRelevant(operator, subject) { if (operator && CUSTOM_OPERATORS.has(operator)) { const { partitionColumn } = this.props; return partitionColumn && subject && subject === partitionColumn; } return !( (this.props.datasource.type === 'druid' && TABLE_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.datasource.type === 'table' && DRUID_ONLY_OPERATORS.indexOf(operator) >= 0) || (this.props.adhocFilter.clause === CLAUSES.HAVING && HAVING_OPERATORS.indexOf(operator) === -1) ); } focusComparator(ref, shouldFocus) { if (ref && shouldFocus) { ref.focus(); } } optionsRemaining() { const { suggestions } = this.state; const { comparator } = this.props.adhocFilter; // if select is multi/value is array, we show the options not selected const valuesFromSuggestionsLength = Array.isArray(comparator) ? comparator.filter(v => suggestions.includes(v)).length : 0; return suggestions?.length - valuesFromSuggestionsLength ?? 0; } createSuggestionsPlaceholder() { const optionsRemaining = this.optionsRemaining(); const placeholder = t('%s option(s)', optionsRemaining); return optionsRemaining ? placeholder : ''; } renderSubjectOptionLabel(option) { return <FilterDefinitionOption option={option} />; } render() { const { adhocFilter, options, datasource } = this.props; let columns = options; const { subject, operator, comparator } = adhocFilter; const subjectSelectProps = { value: subject ?? undefined, onChange: this.onSubjectChange, notFoundContent: t( 'No such column found. To filter on a metric, try the Custom SQL tab.', ), filterOption: (input, option) => option.filterBy.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !subject, }; if (datasource.type === 'druid') { subjectSelectProps.placeholder = t( '%s column(s) and metric(s)', columns.length, ); } else { // we cannot support simple ad-hoc filters for metrics because we don't know what type // the value should be cast to (without knowing the output type of the aggregate, which // becomes a rather complicated problem) subjectSelectProps.placeholder = adhocFilter.clause === CLAUSES.WHERE ? t('%s column(s)', columns.length) : t('To filter on a metric, use Custom SQL tab.'); columns = options.filter(option => option.column_name); } const operatorSelectProps = { placeholder: t( '%s operator(s)', OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject)) .length, ), // like AGGREGTES_OPTIONS, operator options are string value: operator, onChange: this.onOperatorChange, filterOption: (input, option) => option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0, autoFocus: !!subjectSelectProps.value && !operator, }; const focusComparator = !!subjectSelectProps.value && !!operatorSelectProps.value; const comparatorSelectProps = { allowClear: true, showSearch: true, mode: MULTI_OPERATORS.has(operator) && 'tags', tokenSeparators: [',', '\n', '\t', ';'], loading: this.state.loading, value: comparator, onChange: this.onComparatorChange, notFoundContent: t('Type a value here'), disabled: DISABLE_INPUT_OPERATORS.includes(operator), placeholder: this.createSuggestionsPlaceholder(), labelText: comparator?.length > 0 && this.createSuggestionsPlaceholder(), autoFocus: focusComparator, }; return ( <> <FormGroup className="adhoc-filter-simple-column-dropdown"> <Select {...this.selectProps} {...subjectSelectProps} name="filter-column" > {columns.map(column => ( <Select.Option value={column.id || column.optionName} filterBy={ column.saved_metric_name || column.column_name || column.label } key={column.id || column.optionName} > {this.renderSubjectOptionLabel(column)} </Select.Option> ))} </Select> </FormGroup> <FormGroup> <Select {...this.selectProps} {...operatorSelectProps} name="filter-operator" > {OPERATORS_OPTIONS.filter(op => this.isOperatorRelevant(op, subject), ).map(option => ( <Select.Option value={option} key={option}> {translateOperator(option)} </Select.Option> ))} </Select> </FormGroup> <FormGroup data-test="adhoc-filter-simple-value"> {MULTI_OPERATORS.has(operator) || this.state.suggestions.length > 0 ? ( <SelectWithLabel name="filter-value" {...comparatorSelectProps}> {this.state.suggestions.map(suggestion => ( <Select.Option value={suggestion} key={suggestion}> {suggestion} </Select.Option> ))} </SelectWithLabel> ) : ( <Input name="filter-value" ref={ref => this.focusComparator(ref, focusComparator)} onChange={this.onInputComparatorChange} value={comparator} placeholder={t('Filter value (case sensitive)')} disabled={DISABLE_INPUT_OPERATORS.includes(operator)} /> )} </FormGroup> </> ); } } AdhocFilterEditPopoverSimpleTabContent.propTypes = propTypes; AdhocFilterEditPopoverSimpleTabContent.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent.jsx
1
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.004327205941081047, 0.0005060521652922034, 0.00016397767467424273, 0.0001734347897581756, 0.0008117865072563291 ]
{ "id": 6, "code_window": [ " <FormLabel>\n", " <strong>{t('aggregate')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-aggregate\" {...aggregateSelectProps}>\n", " {AGGREGATES_OPTIONS.map(option => (\n", " <Select.Option value={option} key={option}>\n", " {option}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...aggregateSelectProps}\n", " name=\"select-aggregate\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 393 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import PropTypes from 'prop-types'; import { ClassNames } from '@emotion/core'; import { styled, useTheme } from '@superset-ui/core'; import { Tooltip } from 'src/common/components/Tooltip'; const propTypes = { column: PropTypes.object.isRequired, }; const StyledTooltip = (props: any) => { const theme = useTheme(); return ( <ClassNames> {({ css }) => ( <Tooltip overlayClassName={css` .ant-tooltip-inner { max-width: ${theme.gridUnit * 125}px; word-wrap: break-word; text-align: center; pre { background: transparent; border: none; text-align: left; color: ${theme.colors.grayscale.light5}; font-size: ${theme.typography.sizes.xs}px; } } `} {...props} /> )} </ClassNames> ); }; const Hr = styled.hr` margin-top: ${({ theme }) => theme.gridUnit * 1.5}px; `; const iconMap = { pk: 'fa-key', fk: 'fa-link', index: 'fa-bookmark', }; const tooltipTitleMap = { pk: 'Primary key', fk: 'Foreign key', index: 'Index', }; export type ColumnKeyTypeType = keyof typeof tooltipTitleMap; interface ColumnElementProps { column: { name: string; keys?: { type: ColumnKeyTypeType }[]; type: string; }; } export default function ColumnElement({ column }: ColumnElementProps) { let columnName: React.ReactNode = column.name; let icons; if (column.keys && column.keys.length > 0) { columnName = <strong>{column.name}</strong>; icons = column.keys.map((key, i) => ( <span key={i} className="ColumnElement"> <StyledTooltip placement="right" title={ <> <strong>{tooltipTitleMap[key.type]}</strong> <Hr /> <pre className="text-small"> {JSON.stringify(key, null, ' ')} </pre> </> } > <i className={`fa text-muted m-l-2 ${iconMap[key.type]}`} /> </StyledTooltip> </span> )); } return ( <div className="clearfix table-column"> <div className="pull-left m-l-10 col-name"> {columnName} {icons} </div> <div className="pull-right text-muted"> <small> {column.type}</small> </div> </div> ); } ColumnElement.propTypes = propTypes;
superset-frontend/src/SqlLab/components/ColumnElement.tsx
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0001872060092864558, 0.0001729403156787157, 0.00016395282000303268, 0.00017252578982152045, 0.000006252192633837694 ]
{ "id": 6, "code_window": [ " <FormLabel>\n", " <strong>{t('aggregate')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-aggregate\" {...aggregateSelectProps}>\n", " {AGGREGATES_OPTIONS.map(option => (\n", " <Select.Option value={option} key={option}>\n", " {option}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...aggregateSelectProps}\n", " name=\"select-aggregate\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 393 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import PropTypes from 'prop-types'; import { t } from '@superset-ui/core'; import EditableTitle from '../../components/EditableTitle'; import TooltipWrapper from '../../components/TooltipWrapper'; import SliceHeaderControls from './SliceHeaderControls'; import FiltersBadge from '../containers/FiltersBadge'; const propTypes = { innerRef: PropTypes.func, slice: PropTypes.object.isRequired, isExpanded: PropTypes.bool, isCached: PropTypes.arrayOf(PropTypes.bool), cachedDttm: PropTypes.arrayOf(PropTypes.string), updatedDttm: PropTypes.number, updateSliceName: PropTypes.func, toggleExpandSlice: PropTypes.func, forceRefresh: PropTypes.func, exploreChart: PropTypes.func, exportCSV: PropTypes.func, editMode: PropTypes.bool, annotationQuery: PropTypes.object, annotationError: PropTypes.object, sliceName: PropTypes.string, supersetCanExplore: PropTypes.bool, supersetCanCSV: PropTypes.bool, sliceCanEdit: PropTypes.bool, componentId: PropTypes.string.isRequired, dashboardId: PropTypes.number.isRequired, filters: PropTypes.object.isRequired, addDangerToast: PropTypes.func.isRequired, handleToggleFullSize: PropTypes.func.isRequired, chartStatus: PropTypes.string.isRequired, }; const defaultProps = { innerRef: null, forceRefresh: () => ({}), updateSliceName: () => ({}), toggleExpandSlice: () => ({}), exploreChart: () => ({}), exportCSV: () => ({}), editMode: false, annotationQuery: {}, annotationError: {}, cachedDttm: null, updatedDttm: null, isCached: [], isExpanded: [], sliceName: '', supersetCanExplore: false, supersetCanCSV: false, sliceCanEdit: false, }; const annoationsLoading = t('Annotation layers are still loading.'); const annoationsError = t('One ore more annotation layers failed loading.'); class SliceHeader extends React.PureComponent { render() { const { slice, isExpanded, isCached, cachedDttm, updatedDttm, toggleExpandSlice, forceRefresh, exploreChart, exportCSV, innerRef, sliceName, supersetCanExplore, supersetCanCSV, sliceCanEdit, editMode, updateSliceName, annotationQuery, annotationError, componentId, dashboardId, addDangerToast, handleToggleFullSize, isFullSize, chartStatus, } = this.props; return ( <div className="chart-header" ref={innerRef}> <div className="header-title"> <EditableTitle title={ sliceName || (editMode ? '---' // this makes an empty title clickable : '') } canEdit={editMode} emptyText="" onSaveTitle={updateSliceName} showTooltip={false} /> {!!Object.values(annotationQuery).length && ( <TooltipWrapper label="annotations-loading" placement="top" tooltip={annoationsLoading} > <i className="fa fa-refresh warning" /> </TooltipWrapper> )} {!!Object.values(annotationError).length && ( <TooltipWrapper label="annoation-errors" placement="top" tooltip={annoationsError} > <i className="fa fa-exclamation-circle danger" /> </TooltipWrapper> )} </div> <div className="header-controls"> {!editMode && ( <> <FiltersBadge chartId={slice.slice_id} /> <SliceHeaderControls slice={slice} isCached={isCached} isExpanded={isExpanded} cachedDttm={cachedDttm} updatedDttm={updatedDttm} toggleExpandSlice={toggleExpandSlice} forceRefresh={forceRefresh} exploreChart={exploreChart} exportCSV={exportCSV} supersetCanExplore={supersetCanExplore} supersetCanCSV={supersetCanCSV} sliceCanEdit={sliceCanEdit} componentId={componentId} dashboardId={dashboardId} addDangerToast={addDangerToast} handleToggleFullSize={handleToggleFullSize} isFullSize={isFullSize} chartStatus={chartStatus} /> </> )} </div> </div> ); } } SliceHeader.propTypes = propTypes; SliceHeader.defaultProps = defaultProps; export default SliceHeader;
superset-frontend/src/dashboard/components/SliceHeader.jsx
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.00017823238158598542, 0.00017263556947000325, 0.00016419609892182052, 0.00017418983043171465, 0.000004326678208599333 ]
{ "id": 6, "code_window": [ " <FormLabel>\n", " <strong>{t('aggregate')}</strong>\n", " </FormLabel>\n", " <Select name=\"select-aggregate\" {...aggregateSelectProps}>\n", " {AGGREGATES_OPTIONS.map(option => (\n", " <Select.Option value={option} key={option}>\n", " {option}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Select\n", " {...aggregateSelectProps}\n", " name=\"select-aggregate\"\n", " getPopupContainer={triggerNode => triggerNode.parentNode}\n", " >\n" ], "file_path": "superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover.jsx", "type": "replace", "edit_start_line_idx": 393 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. slice_name: Seasonality of Revenue (per Product Line) viz_type: horizon params: adhoc_filters: [] datasource: 23__table granularity_sqla: order_date groupby: - product_line horizon_color_scale: series metrics: - aggregate: SUM column: column_name: sales description: null expression: null filterable: true groupby: true id: 917 is_dttm: false optionName: _col_Sales python_date_format: null type: DOUBLE PRECISION verbose_name: null expressionType: SIMPLE hasCustomLabel: false isNew: false label: (Sales) optionName: metric_e3kxby3hnjs_nfd4adbcnsn sqlExpression: null order_desc: true queryFields: groupby: groupby metrics: metrics row_limit: null series_height: '25' slice_id: 2811 time_range: No filter time_range_endpoints: - inclusive - exclusive url_params: {} viz_type: horizon cache_timeout: null uuid: cf0da099-b3ab-4d94-ab62-cf353ac3c611 version: 1.0.0 dataset_uuid: e8623bb9-5e00-f531-506a-19607f5f8005
superset/examples/configs/charts/Seasonality_of_Revenue_per_Product_Line.yaml
0
https://github.com/apache/superset/commit/1603e82a035073d3e90cc37c7e24bee380d22035
[ 0.0001780806778697297, 0.0001749235379975289, 0.0001681730936979875, 0.00017656944692134857, 0.0000036567294046108145 ]
{ "id": 0, "code_window": [ "import React, { memo, useEffect, useCallback } from 'react';\n", "import { usePrevious } from 'react-use';\n", "import { isEqual } from 'lodash';\n", "import { css, cx } from '@emotion/css';\n", "import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui';\n", "import { PromQuery } from '../types';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, useCallback } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 0 }
import React, { memo, useEffect, useCallback } from 'react'; import { usePrevious } from 'react-use'; import { isEqual } from 'lodash'; import { css, cx } from '@emotion/css'; import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui'; import { PromQuery } from '../types'; import { PromExemplarField } from './PromExemplarField'; import { PrometheusDatasource } from '../datasource'; export interface PromExploreExtraFieldProps { query: PromQuery; onChange: (value: PromQuery) => void; onRunQuery: () => void; datasource: PrometheusDatasource; } export const PromExploreExtraField: React.FC<PromExploreExtraFieldProps> = memo( ({ query, datasource, onChange, onRunQuery }) => { const rangeOptions = [ { value: 'range', label: 'Range', description: 'Run query over a range of time.' }, { value: 'instant', label: 'Instant', description: 'Run query against a single point in time. For this query, the "To" time is used.', }, { value: 'both', label: 'Both', description: 'Run an Instant query and a Range query.' }, ]; const prevQuery = usePrevious(query); // Setting default values useEffect(() => { if (query.exemplar === undefined) { onChange({ ...query, exemplar: true }); } if (!query.instant && !query.range) { onChange({ ...query, instant: true, range: true }); } }, [onChange, query]); const onExemplarChange = useCallback( (exemplar: boolean) => { if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) { onChange({ ...query, exemplar }); } }, [prevQuery, query, onChange] ); function onChangeQueryStep(interval: string) { onChange({ ...query, interval }); } function onStepChange(e: React.SyntheticEvent<HTMLInputElement>) { if (e.currentTarget.value !== query.interval) { onChangeQueryStep(e.currentTarget.value); } } function onReturnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) { if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey)) { onRunQuery(); } } function onQueryTypeChange(queryType: string) { let nextQuery; if (queryType === 'instant') { nextQuery = { ...query, instant: true, range: false }; } else if (queryType === 'range') { nextQuery = { ...query, instant: false, range: true }; } else { nextQuery = { ...query, instant: true, range: true }; } onChange(nextQuery); } return ( <div aria-label="Prometheus extra field" className="gf-form-inline"> {/*Query type field*/} <div data-testid="queryTypeField" className={cx( 'gf-form explore-input-margin', css` flex-wrap: nowrap; ` )} aria-label="Query type field" > <InlineFormLabel width="auto">Query type</InlineFormLabel> <RadioButtonGroup options={rangeOptions} value={query.range === query.instant ? 'both' : query.instant ? 'instant' : 'range'} onChange={onQueryTypeChange} /> </div> {/*Step field*/} <div data-testid="stepField" className={cx( 'gf-form', css` flex-wrap: nowrap; ` )} aria-label="Step field" > <InlineFormLabel width={5} tooltip={ 'Time units can be used here, for example: 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)' } > Step </InlineFormLabel> <input type={'text'} className="gf-form-input width-4" placeholder={'auto'} onChange={onStepChange} onKeyDown={onReturnKeyDown} value={query.interval ?? ''} /> </div> <PromExemplarField onChange={onExemplarChange} datasource={datasource} query={query} /> </div> ); } );
public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx
1
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.991878867149353, 0.07134703546762466, 0.00016771189984865487, 0.0001841456105466932, 0.2553103566169739 ]
{ "id": 0, "code_window": [ "import React, { memo, useEffect, useCallback } from 'react';\n", "import { usePrevious } from 'react-use';\n", "import { isEqual } from 'lodash';\n", "import { css, cx } from '@emotion/css';\n", "import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui';\n", "import { PromQuery } from '../types';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, useCallback } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 0 }
apiVersion: 1 datasources: - name: invalid-access type: prometheus access: INVALID_ACCESS
pkg/services/provisioning/datasources/testdata/invalid-access/invalid-access.yaml
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017364576342515647, 0.00017364576342515647, 0.00017364576342515647, 0.00017364576342515647, 0 ]
{ "id": 0, "code_window": [ "import React, { memo, useEffect, useCallback } from 'react';\n", "import { usePrevious } from 'react-use';\n", "import { isEqual } from 'lodash';\n", "import { css, cx } from '@emotion/css';\n", "import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui';\n", "import { PromQuery } from '../types';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, useCallback } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 0 }
import { AnnotationQueryRequest, DataSourceInstanceSettings, dateTime } from '@grafana/data'; import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__ import { GrafanaDatasource } from './datasource'; import { GrafanaAnnotationQuery, GrafanaAnnotationType, GrafanaQuery } from './types'; jest.mock('@grafana/runtime', () => ({ ...((jest.requireActual('@grafana/runtime') as unknown) as object), getBackendSrv: () => backendSrv, getTemplateSrv: () => ({ replace: (val: string) => { return val.replace('$var2', 'replaced__delimiter__replaced2').replace('$var', 'replaced'); }, }), })); describe('grafana data source', () => { const getMock = jest.spyOn(backendSrv, 'get'); beforeEach(() => { jest.clearAllMocks(); }); describe('when executing an annotations query', () => { let calledBackendSrvParams: any; let ds: GrafanaDatasource; beforeEach(() => { getMock.mockImplementation((url: string, options: any) => { calledBackendSrvParams = options; return Promise.resolve([]); }); ds = new GrafanaDatasource({} as DataSourceInstanceSettings); }); describe('with tags that have template variables', () => { const options = setupAnnotationQueryOptions({ tags: ['tag1:$var'] }); beforeEach(() => { return ds.getAnnotations(options); }); it('should interpolate template variables in tags in query options', () => { expect(calledBackendSrvParams.tags[0]).toBe('tag1:replaced'); }); }); describe('with tags that have multi value template variables', () => { const options = setupAnnotationQueryOptions({ tags: ['$var2'] }); beforeEach(() => { return ds.getAnnotations(options); }); it('should interpolate template variables in tags in query options', () => { expect(calledBackendSrvParams.tags[0]).toBe('replaced'); expect(calledBackendSrvParams.tags[1]).toBe('replaced2'); }); }); describe('with type dashboard', () => { const options = setupAnnotationQueryOptions( { type: GrafanaAnnotationType.Dashboard, tags: ['tag1'], }, { id: 1 } ); beforeEach(() => { return ds.getAnnotations(options); }); it('should remove tags from query options', () => { expect(calledBackendSrvParams.tags).toBe(undefined); }); }); }); }); function setupAnnotationQueryOptions(annotation: Partial<GrafanaAnnotationQuery>, dashboard?: { id: number }) { return ({ annotation: { target: annotation, }, dashboard, range: { from: dateTime(1432288354), to: dateTime(1432288401), }, rangeRaw: { from: 'now-24h', to: 'now' }, } as unknown) as AnnotationQueryRequest<GrafanaQuery>; }
public/app/plugins/datasource/grafana/datasource.test.ts
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00025495365844108164, 0.0001804628991521895, 0.00016283745935652405, 0.00017374451272189617, 0.000025192901375703514 ]
{ "id": 0, "code_window": [ "import React, { memo, useEffect, useCallback } from 'react';\n", "import { usePrevious } from 'react-use';\n", "import { isEqual } from 'lodash';\n", "import { css, cx } from '@emotion/css';\n", "import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui';\n", "import { PromQuery } from '../types';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, useCallback } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 0 }
import UrlBuilder from './url_builder'; describe('AzureMonitorUrlBuilder', () => { describe('when metric definition is Microsoft.NetApp/netAppAccounts/capacityPools/volumes', () => { it('should build the getMetricNamespaces url in the even longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamespacesUrl( '', 'sub1', 'rg', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'rn1/rn2/rn3', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.NetApp/netAppAccounts/rn1/capacityPools/rn2/volumes/rn3/' + 'providers/microsoft.insights/metricNamespaces?api-version=2017-05-01-preview' ); }); }); describe('when metric definition is Microsoft.Sql/servers/databases', () => { it('should build the getMetricNamespaces url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamespacesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers/databases', 'rn1/rn2', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn1/databases/rn2/' + 'providers/microsoft.insights/metricNamespaces?api-version=2017-05-01-preview' ); }); }); describe('when metric definition is Microsoft.Sql/servers', () => { it('should build the getMetricNamespaces url in the shorter format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamespacesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers', 'rn', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn/' + 'providers/microsoft.insights/metricNamespaces?api-version=2017-05-01-preview' ); }); }); describe('when metric definition is Microsoft.NetApp/netAppAccounts/capacityPools/volumes and the metricNamespace is default', () => { it('should build the getMetricNames url in the even longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'rn1/rn2/rn3', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.NetApp/netAppAccounts/rn1/capacityPools/rn2/volumes/rn3/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Sql/servers/databases and the metricNamespace is default', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers/databases', 'rn1/rn2', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn1/databases/rn2/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Sql/servers and the metricNamespace is default', () => { it('should build the getMetricNames url in the shorter format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers', 'rn', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/blobServices and the metricNamespace is default', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/blobServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/blobServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/fileServices and the metricNamespace is default', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/fileServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/fileServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/tableServices and the metricNamespace is default', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/tableServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/tableServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/queueServices and the metricNamespace is default', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/queueServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/queueServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); });
public/app/plugins/datasource/grafana-azure-monitor-datasource/azure_monitor/url_builder.test.ts
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017760317132342607, 0.00017520548135507852, 0.0001715828402666375, 0.00017531492630951107, 0.0000017353311250190018 ]
{ "id": 1, "code_window": [ " ];\n", "\n", " const prevQuery = usePrevious(query);\n", "\n", " // Setting default values\n", " useEffect(() => {\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n", " const onExemplarChange = useCallback(\n", " (exemplar: boolean) => {\n", " if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 30 }
import React, { memo, useEffect, useCallback } from 'react'; import { usePrevious } from 'react-use'; import { isEqual } from 'lodash'; import { css, cx } from '@emotion/css'; import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui'; import { PromQuery } from '../types'; import { PromExemplarField } from './PromExemplarField'; import { PrometheusDatasource } from '../datasource'; export interface PromExploreExtraFieldProps { query: PromQuery; onChange: (value: PromQuery) => void; onRunQuery: () => void; datasource: PrometheusDatasource; } export const PromExploreExtraField: React.FC<PromExploreExtraFieldProps> = memo( ({ query, datasource, onChange, onRunQuery }) => { const rangeOptions = [ { value: 'range', label: 'Range', description: 'Run query over a range of time.' }, { value: 'instant', label: 'Instant', description: 'Run query against a single point in time. For this query, the "To" time is used.', }, { value: 'both', label: 'Both', description: 'Run an Instant query and a Range query.' }, ]; const prevQuery = usePrevious(query); // Setting default values useEffect(() => { if (query.exemplar === undefined) { onChange({ ...query, exemplar: true }); } if (!query.instant && !query.range) { onChange({ ...query, instant: true, range: true }); } }, [onChange, query]); const onExemplarChange = useCallback( (exemplar: boolean) => { if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) { onChange({ ...query, exemplar }); } }, [prevQuery, query, onChange] ); function onChangeQueryStep(interval: string) { onChange({ ...query, interval }); } function onStepChange(e: React.SyntheticEvent<HTMLInputElement>) { if (e.currentTarget.value !== query.interval) { onChangeQueryStep(e.currentTarget.value); } } function onReturnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) { if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey)) { onRunQuery(); } } function onQueryTypeChange(queryType: string) { let nextQuery; if (queryType === 'instant') { nextQuery = { ...query, instant: true, range: false }; } else if (queryType === 'range') { nextQuery = { ...query, instant: false, range: true }; } else { nextQuery = { ...query, instant: true, range: true }; } onChange(nextQuery); } return ( <div aria-label="Prometheus extra field" className="gf-form-inline"> {/*Query type field*/} <div data-testid="queryTypeField" className={cx( 'gf-form explore-input-margin', css` flex-wrap: nowrap; ` )} aria-label="Query type field" > <InlineFormLabel width="auto">Query type</InlineFormLabel> <RadioButtonGroup options={rangeOptions} value={query.range === query.instant ? 'both' : query.instant ? 'instant' : 'range'} onChange={onQueryTypeChange} /> </div> {/*Step field*/} <div data-testid="stepField" className={cx( 'gf-form', css` flex-wrap: nowrap; ` )} aria-label="Step field" > <InlineFormLabel width={5} tooltip={ 'Time units can be used here, for example: 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)' } > Step </InlineFormLabel> <input type={'text'} className="gf-form-input width-4" placeholder={'auto'} onChange={onStepChange} onKeyDown={onReturnKeyDown} value={query.interval ?? ''} /> </div> <PromExemplarField onChange={onExemplarChange} datasource={datasource} query={query} /> </div> ); } );
public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx
1
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.9979281425476074, 0.21574802696704865, 0.0001658115943428129, 0.001447135116904974, 0.39630985260009766 ]
{ "id": 1, "code_window": [ " ];\n", "\n", " const prevQuery = usePrevious(query);\n", "\n", " // Setting default values\n", " useEffect(() => {\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n", " const onExemplarChange = useCallback(\n", " (exemplar: boolean) => {\n", " if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 30 }
package expr import ( "context" "encoding/json" "fmt" "time" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana/pkg/expr/classic" "github.com/grafana/grafana/pkg/expr/mathexp" "github.com/grafana/grafana/pkg/infra/log" "gonum.org/v1/gonum/graph/simple" ) var ( logger = log.New("expr") ) // baseNode includes common properties used across DPNodes. type baseNode struct { id int64 refID string } type rawNode struct { RefID string `json:"refId"` Query map[string]interface{} QueryType string TimeRange TimeRange DatasourceUID string } func (rn *rawNode) GetDatasourceName() (string, error) { rawDs, ok := rn.Query["datasource"] if !ok { return "", nil } dsName, ok := rawDs.(string) if !ok { return "", fmt.Errorf("expted datasource identifier to be a string, got %T", rawDs) } return dsName, nil } func (rn *rawNode) GetCommandType() (c CommandType, err error) { rawType, ok := rn.Query["type"] if !ok { return c, fmt.Errorf("no expression command type in query for refId %v", rn.RefID) } typeString, ok := rawType.(string) if !ok { return c, fmt.Errorf("expected expression command type to be a string, got type %T", rawType) } return ParseCommandType(typeString) } // String returns a string representation of the node. In particular for // %v formatting in error messages. func (b *baseNode) String() string { return b.refID } // CMDNode is a DPNode that holds an expression command. type CMDNode struct { baseNode CMDType CommandType Command Command } // ID returns the id of the node so it can fulfill the gonum's graph Node interface. func (b *baseNode) ID() int64 { return b.id } // RefID returns the refId of the node. func (b *baseNode) RefID() string { return b.refID } // NodeType returns the data pipeline node type. func (gn *CMDNode) NodeType() NodeType { return TypeCMDNode } // Execute runs the node and adds the results to vars. If the node requires // other nodes they must have already been executed and their results must // already by in vars. func (gn *CMDNode) Execute(ctx context.Context, vars mathexp.Vars, s *Service) (mathexp.Results, error) { return gn.Command.Execute(ctx, vars) } func buildCMDNode(dp *simple.DirectedGraph, rn *rawNode) (*CMDNode, error) { commandType, err := rn.GetCommandType() if err != nil { return nil, fmt.Errorf("invalid expression command type in '%v'", rn.RefID) } node := &CMDNode{ baseNode: baseNode{ id: dp.NewNode().ID(), refID: rn.RefID, }, CMDType: commandType, } switch commandType { case TypeMath: node.Command, err = UnmarshalMathCommand(rn) case TypeReduce: node.Command, err = UnmarshalReduceCommand(rn) case TypeResample: node.Command, err = UnmarshalResampleCommand(rn) case TypeClassicConditions: node.Command, err = classic.UnmarshalConditionsCmd(rn.Query, rn.RefID) default: return nil, fmt.Errorf("expression command type '%v' in '%v' not implemented", commandType, rn.RefID) } if err != nil { return nil, err } return node, nil } const ( defaultIntervalMS = int64(64) defaultMaxDP = int64(5000) ) // DSNode is a DPNode that holds a datasource request. type DSNode struct { baseNode query json.RawMessage datasourceID int64 datasourceUID string orgID int64 queryType string timeRange TimeRange intervalMS int64 maxDP int64 request Request } // NodeType returns the data pipeline node type. func (dn *DSNode) NodeType() NodeType { return TypeDatasourceNode } func (s *Service) buildDSNode(dp *simple.DirectedGraph, rn *rawNode, req *Request) (*DSNode, error) { encodedQuery, err := json.Marshal(rn.Query) if err != nil { return nil, err } dsNode := &DSNode{ baseNode: baseNode{ id: dp.NewNode().ID(), refID: rn.RefID, }, orgID: req.OrgId, query: json.RawMessage(encodedQuery), queryType: rn.QueryType, intervalMS: defaultIntervalMS, maxDP: defaultMaxDP, timeRange: rn.TimeRange, request: *req, } rawDsID, ok := rn.Query["datasourceId"] switch ok { case true: floatDsID, ok := rawDsID.(float64) if !ok { return nil, fmt.Errorf("expected datasourceId to be a float64, got type %T for refId %v", rawDsID, rn.RefID) } dsNode.datasourceID = int64(floatDsID) default: if rn.DatasourceUID == "" { return nil, fmt.Errorf("neither datasourceId or datasourceUid in expression data source request for refId %v", rn.RefID) } dsNode.datasourceUID = rn.DatasourceUID } var floatIntervalMS float64 if rawIntervalMS, ok := rn.Query["intervalMs"]; ok { if floatIntervalMS, ok = rawIntervalMS.(float64); !ok { return nil, fmt.Errorf("expected intervalMs to be an float64, got type %T for refId %v", rawIntervalMS, rn.RefID) } dsNode.intervalMS = int64(floatIntervalMS) } var floatMaxDP float64 if rawMaxDP, ok := rn.Query["maxDataPoints"]; ok { if floatMaxDP, ok = rawMaxDP.(float64); !ok { return nil, fmt.Errorf("expected maxDataPoints to be an float64, got type %T for refId %v", rawMaxDP, rn.RefID) } dsNode.maxDP = int64(floatMaxDP) } return dsNode, nil } // Execute runs the node and adds the results to vars. If the node requires // other nodes they must have already been executed and their results must // already by in vars. func (dn *DSNode) Execute(ctx context.Context, vars mathexp.Vars, s *Service) (mathexp.Results, error) { pc := backend.PluginContext{ OrgID: dn.orgID, DataSourceInstanceSettings: &backend.DataSourceInstanceSettings{ ID: dn.datasourceID, UID: dn.datasourceUID, }, } q := []backend.DataQuery{ { RefID: dn.refID, MaxDataPoints: dn.maxDP, Interval: time.Duration(int64(time.Millisecond) * dn.intervalMS), JSON: dn.query, TimeRange: backend.TimeRange{ From: dn.timeRange.From, To: dn.timeRange.To, }, QueryType: dn.queryType, }, } resp, err := s.queryData(ctx, &backend.QueryDataRequest{ PluginContext: pc, Queries: q, Headers: dn.request.Headers, }) if err != nil { return mathexp.Results{}, err } vals := make([]mathexp.Value, 0) for refID, qr := range resp.Responses { if qr.Error != nil { return mathexp.Results{}, fmt.Errorf("failed to execute query %v: %w", refID, qr.Error) } if len(qr.Frames) == 1 { frame := qr.Frames[0] if frame.TimeSeriesSchema().Type == data.TimeSeriesTypeNot && isNumberTable(frame) { logger.Debug("expression datasource query (numberSet)", "query", refID) numberSet, err := extractNumberSet(frame) if err != nil { return mathexp.Results{}, err } for _, n := range numberSet { vals = append(vals, n) } return mathexp.Results{ Values: vals, }, nil } } for _, frame := range qr.Frames { logger.Debug("expression datasource query (seriesSet)", "query", refID) series, err := WideToMany(frame) if err != nil { return mathexp.Results{}, err } for _, s := range series { vals = append(vals, s) } } } return mathexp.Results{ Values: vals, }, nil } func isNumberTable(frame *data.Frame) bool { if frame == nil || frame.Fields == nil { return false } numericCount := 0 stringCount := 0 otherCount := 0 for _, field := range frame.Fields { fType := field.Type() switch { case fType.Numeric(): numericCount++ case fType == data.FieldTypeString || fType == data.FieldTypeNullableString: stringCount++ default: otherCount++ } } return numericCount == 1 && otherCount == 0 } func extractNumberSet(frame *data.Frame) ([]mathexp.Number, error) { numericField := 0 stringFieldIdxs := []int{} stringFieldNames := []string{} for i, field := range frame.Fields { fType := field.Type() switch { case fType.Numeric(): numericField = i case fType == data.FieldTypeString || fType == data.FieldTypeNullableString: stringFieldIdxs = append(stringFieldIdxs, i) stringFieldNames = append(stringFieldNames, field.Name) } } numbers := make([]mathexp.Number, frame.Rows()) for rowIdx := 0; rowIdx < frame.Rows(); rowIdx++ { val, _ := frame.FloatAt(numericField, rowIdx) var labels data.Labels for i := 0; i < len(stringFieldIdxs); i++ { if i == 0 { labels = make(data.Labels) } key := stringFieldNames[i] // TODO check for duplicate string column names val, _ := frame.ConcreteAt(stringFieldIdxs[i], rowIdx) labels[key] = val.(string) // TODO check assertion / return error } n := mathexp.NewNumber("", labels) n.SetValue(&val) numbers[rowIdx] = n } return numbers, nil } // WideToMany converts a data package wide type Frame to one or multiple Series. A series // is created for each value type column of wide frame. // // This might not be a good idea long term, but works now as an adapter/shim. func WideToMany(frame *data.Frame) ([]mathexp.Series, error) { tsSchema := frame.TimeSeriesSchema() if tsSchema.Type != data.TimeSeriesTypeWide { return nil, fmt.Errorf("input data must be a wide series but got type %s (input refid)", tsSchema.Type) } if len(tsSchema.ValueIndices) == 1 { s, err := mathexp.SeriesFromFrame(frame) if err != nil { return nil, err } return []mathexp.Series{s}, nil } series := []mathexp.Series{} for _, valIdx := range tsSchema.ValueIndices { l := frame.Rows() f := data.NewFrameOfFieldTypes(frame.Name, l, frame.Fields[tsSchema.TimeIndex].Type(), frame.Fields[valIdx].Type()) f.Fields[0].Name = frame.Fields[tsSchema.TimeIndex].Name f.Fields[1].Name = frame.Fields[valIdx].Name if frame.Fields[valIdx].Labels != nil { f.Fields[1].Labels = frame.Fields[valIdx].Labels.Copy() } for i := 0; i < l; i++ { f.SetRow(i, frame.Fields[tsSchema.TimeIndex].CopyAt(i), frame.Fields[valIdx].CopyAt(i)) } s, err := mathexp.SeriesFromFrame(f) if err != nil { return nil, err } series = append(series, s) } return series, nil }
pkg/expr/nodes.go
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00031132856383919716, 0.00017476426728535444, 0.0001595185458427295, 0.00016974954633042216, 0.000024848659450071864 ]
{ "id": 1, "code_window": [ " ];\n", "\n", " const prevQuery = usePrevious(query);\n", "\n", " // Setting default values\n", " useEffect(() => {\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n", " const onExemplarChange = useCallback(\n", " (exemplar: boolean) => {\n", " if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 30 }
// Copyright (c) 2017 Uber Technologies, Inc. // // 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. import * as React from 'react'; import { css, cx } from '@emotion/css'; import { TUpdateViewRangeTimeFunction, ViewRangeTime, ViewRangeTimeUpdate } from '../types'; import { TNil } from '../../types'; import DraggableManager, { DraggableBounds, DraggingUpdate } from '../../utils/DraggableManager'; import { createStyle } from '../../Theme'; // exported for testing export const getStyles = createStyle(() => { return { TimelineViewingLayer: css` label: TimelineViewingLayer; bottom: 0; cursor: vertical-text; left: 0; position: absolute; right: 0; top: 0; `, TimelineViewingLayerCursorGuide: css` label: TimelineViewingLayerCursorGuide; position: absolute; top: 0; bottom: 0; left: 0; width: 1px; background-color: red; `, TimelineViewingLayerDragged: css` label: TimelineViewingLayerDragged; position: absolute; top: 0; bottom: 0; `, TimelineViewingLayerDraggedDraggingLeft: css` label: TimelineViewingLayerDraggedDraggingLeft; border-left: 1px solid; `, TimelineViewingLayerDraggedDraggingRight: css` label: TimelineViewingLayerDraggedDraggingRight; border-right: 1px solid; `, TimelineViewingLayerDraggedShiftDrag: css` label: TimelineViewingLayerDraggedShiftDrag; background-color: rgba(68, 68, 255, 0.2); border-color: #44f; `, TimelineViewingLayerDraggedReframeDrag: css` label: TimelineViewingLayerDraggedReframeDrag; background-color: rgba(255, 68, 68, 0.2); border-color: #f44; `, TimelineViewingLayerFullOverlay: css` label: TimelineViewingLayerFullOverlay; bottom: 0; cursor: col-resize; left: 0; position: fixed; right: 0; top: 0; user-select: none; `, }; }); type TimelineViewingLayerProps = { /** * `boundsInvalidator` is an arbitrary prop that lets the component know the * bounds for dragging need to be recalculated. In practice, the name column * width serves fine for this. */ boundsInvalidator: any | null | undefined; updateNextViewRangeTime: (update: ViewRangeTimeUpdate) => void; updateViewRangeTime: TUpdateViewRangeTimeFunction; viewRangeTime: ViewRangeTime; }; type TDraggingLeftLayout = { isDraggingLeft: boolean; left: string; width: string; }; type TOutOfViewLayout = { isOutOfView: true; }; function isOutOfView(layout: TDraggingLeftLayout | TOutOfViewLayout): layout is TOutOfViewLayout { return Reflect.has(layout, 'isOutOfView'); } /** * Map from a sub range to the greater view range, e.g, when the view range is * the middle half ([0.25, 0.75]), a value of 0.25 befomes 3/8. * @returns {number} */ function mapFromViewSubRange(viewStart: number, viewEnd: number, value: number) { return viewStart + value * (viewEnd - viewStart); } /** * Map a value from the view ([0, 1]) to a sub-range, e.g, when the view range is * the middle half ([0.25, 0.75]), a value of 3/8 becomes 1/4. * @returns {number} */ function mapToViewSubRange(viewStart: number, viewEnd: number, value: number) { return (value - viewStart) / (viewEnd - viewStart); } /** * Get the layout for the "next" view range time, e.g. the difference from the * drag start and the drag end. This is driven by `shiftStart`, `shiftEnd` or * `reframe` on `props.viewRangeTime`, not by the current state of the * component. So, it reflects in-progress dragging from the span minimap. */ function getNextViewLayout(start: number, position: number): TDraggingLeftLayout | TOutOfViewLayout { let [left, right] = start < position ? [start, position] : [position, start]; if (left >= 1 || right <= 0) { return { isOutOfView: true }; } if (left < 0) { left = 0; } if (right > 1) { right = 1; } return { isDraggingLeft: start > position, left: `${left * 100}%`, width: `${(right - left) * 100}%`, }; } /** * Render the visual indication of the "next" view range. */ function getMarkers(viewStart: number, viewEnd: number, from: number, to: number, isShift: boolean): React.ReactNode { const mappedFrom = mapToViewSubRange(viewStart, viewEnd, from); const mappedTo = mapToViewSubRange(viewStart, viewEnd, to); const layout = getNextViewLayout(mappedFrom, mappedTo); if (isOutOfView(layout)) { return null; } const { isDraggingLeft, left, width } = layout; const styles = getStyles(); const cls = cx({ [styles.TimelineViewingLayerDraggedDraggingRight]: !isDraggingLeft, [styles.TimelineViewingLayerDraggedReframeDrag]: !isShift, [styles.TimelineViewingLayerDraggedShiftDrag]: isShift, }); return ( <div className={cx(styles.TimelineViewingLayerDragged, styles.TimelineViewingLayerDraggedDraggingLeft, cls)} style={{ left, width }} data-test-id="Dragged" /> ); } /** * `TimelineViewingLayer` is rendered on top of the TimelineHeaderRow time * labels; it handles showing the current view range and handles mouse UX for * modifying it. */ export default class TimelineViewingLayer extends React.PureComponent<TimelineViewingLayerProps> { _draggerReframe: DraggableManager; _root: Element | TNil; constructor(props: TimelineViewingLayerProps) { super(props); this._draggerReframe = new DraggableManager({ getBounds: this._getDraggingBounds, onDragEnd: this._handleReframeDragEnd, onDragMove: this._handleReframeDragUpdate, onDragStart: this._handleReframeDragUpdate, onMouseLeave: this._handleReframeMouseLeave, onMouseMove: this._handleReframeMouseMove, }); this._root = undefined; } UNSAFE_componentWillReceiveProps(nextProps: TimelineViewingLayerProps) { const { boundsInvalidator } = this.props; if (boundsInvalidator !== nextProps.boundsInvalidator) { this._draggerReframe.resetBounds(); } } componentWillUnmount() { this._draggerReframe.dispose(); } _setRoot = (elm: Element | TNil) => { this._root = elm; }; _getDraggingBounds = (): DraggableBounds => { if (!this._root) { throw new Error('invalid state'); } const { left: clientXLeft, width } = this._root.getBoundingClientRect(); return { clientXLeft, width }; }; _handleReframeMouseMove = ({ value }: DraggingUpdate) => { const [viewStart, viewEnd] = this.props.viewRangeTime.current; const cursor = mapFromViewSubRange(viewStart, viewEnd, value); this.props.updateNextViewRangeTime({ cursor }); }; _handleReframeMouseLeave = () => { this.props.updateNextViewRangeTime({ cursor: undefined }); }; _handleReframeDragUpdate = ({ value }: DraggingUpdate) => { const { current, reframe } = this.props.viewRangeTime; const [viewStart, viewEnd] = current; const shift = mapFromViewSubRange(viewStart, viewEnd, value); const anchor = reframe ? reframe.anchor : shift; const update = { reframe: { anchor, shift } }; this.props.updateNextViewRangeTime(update); }; _handleReframeDragEnd = ({ manager, value }: DraggingUpdate) => { const { current, reframe } = this.props.viewRangeTime; const [viewStart, viewEnd] = current; const shift = mapFromViewSubRange(viewStart, viewEnd, value); const anchor = reframe ? reframe.anchor : shift; const [start, end] = shift < anchor ? [shift, anchor] : [anchor, shift]; manager.resetBounds(); this.props.updateViewRangeTime(start, end, 'timeline-header'); }; render() { const { viewRangeTime } = this.props; const { current, cursor, reframe, shiftEnd, shiftStart } = viewRangeTime; const [viewStart, viewEnd] = current; const haveNextTimeRange = reframe != null || shiftEnd != null || shiftStart != null; let cusrorPosition: string | TNil; if (!haveNextTimeRange && cursor != null && cursor >= viewStart && cursor <= viewEnd) { cusrorPosition = `${mapToViewSubRange(viewStart, viewEnd, cursor) * 100}%`; } const styles = getStyles(); return ( <div aria-hidden className={styles.TimelineViewingLayer} ref={this._setRoot} onMouseDown={this._draggerReframe.handleMouseDown} onMouseLeave={this._draggerReframe.handleMouseLeave} onMouseMove={this._draggerReframe.handleMouseMove} data-test-id="TimelineViewingLayer" > {cusrorPosition != null && ( <div className={styles.TimelineViewingLayerCursorGuide} style={{ left: cusrorPosition }} data-test-id="TimelineViewingLayer--cursorGuide" /> )} {reframe != null && getMarkers(viewStart, viewEnd, reframe.anchor, reframe.shift, false)} {shiftEnd != null && getMarkers(viewStart, viewEnd, viewEnd, shiftEnd, true)} {shiftStart != null && getMarkers(viewStart, viewEnd, viewStart, shiftStart, true)} </div> ); } }
packages/jaeger-ui-components/src/TraceTimelineViewer/TimelineHeaderRow/TimelineViewingLayer.tsx
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017726157966535538, 0.00017002530512399971, 0.00016460711776744574, 0.00016952515579760075, 0.0000033768035336834146 ]
{ "id": 1, "code_window": [ " ];\n", "\n", " const prevQuery = usePrevious(query);\n", "\n", " // Setting default values\n", " useEffect(() => {\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n", " const onExemplarChange = useCallback(\n", " (exemplar: boolean) => {\n", " if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx", "type": "replace", "edit_start_line_idx": 30 }
package sqleng import ( "testing" "time" "github.com/google/go-cmp/cmp" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/stretchr/testify/require" "github.com/xorcare/pointer" ) func TestResampleWide(t *testing.T) { tests := []struct { name string input *data.Frame fillMissing *data.FillMissing timeRange backend.TimeRange interval time.Duration output *data.Frame }{ { name: "interval 1s; fill null", fillMissing: &data.FillMissing{Mode: data.FillModeNull}, timeRange: backend.TimeRange{ From: time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), To: time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }, interval: time.Second, input: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(15.0), })), output: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 21, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 22, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 23, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 25, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ nil, pointer.Int64(10), pointer.Int64(12), nil, nil, nil, pointer.Int64(15), nil, nil, }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ nil, pointer.Float64(10.5), pointer.Float64(12.5), nil, nil, nil, pointer.Float64(15.0), nil, nil, })), }, { name: "interval 1s; fill value", fillMissing: &data.FillMissing{Mode: data.FillModeValue, Value: -1}, timeRange: backend.TimeRange{ From: time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), To: time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }, interval: time.Second, input: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(15.0), })), output: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 21, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 22, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 23, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 25, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(-1), pointer.Int64(10), pointer.Int64(12), pointer.Int64(-1), pointer.Int64(-1), pointer.Int64(-1), pointer.Int64(15), pointer.Int64(-1), pointer.Int64(-1), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(-1), pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(-1), pointer.Float64(-1), pointer.Float64(-1), pointer.Float64(15.0), pointer.Float64(-1), pointer.Float64(-1), })), }, { name: "interval 1s; fill previous", fillMissing: &data.FillMissing{Mode: data.FillModePrevious}, timeRange: backend.TimeRange{ From: time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), To: time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }, interval: time.Second, input: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(15.0), })), output: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 21, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 22, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 23, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 25, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ nil, pointer.Int64(10), pointer.Int64(12), pointer.Int64(12), pointer.Int64(12), pointer.Int64(12), pointer.Int64(15), pointer.Int64(15), pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ nil, pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(12.5), pointer.Float64(12.5), pointer.Float64(12.5), pointer.Float64(15.0), pointer.Float64(15.0), pointer.Float64(15.0), })), }, { name: "interval 2s; fill null", fillMissing: &data.FillMissing{Mode: data.FillModeNull}, timeRange: backend.TimeRange{ From: time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), To: time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }, interval: 2 * time.Second, input: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(15.0), })), output: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 18, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 22, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 26, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), nil, pointer.Int64(15), nil, }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), nil, pointer.Float64(15.0), nil, })), }, { name: "interval 1s; fill null; rows outside timerange window", fillMissing: &data.FillMissing{Mode: data.FillModeNull}, timeRange: backend.TimeRange{ From: time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), To: time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }, interval: time.Second, input: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 19, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 27, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(10), pointer.Int64(12), pointer.Int64(15), pointer.Int64(18), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(10.5), pointer.Float64(12.5), pointer.Float64(15.0), pointer.Float64(17.5), })), output: data.NewFrame("wide_test", data.NewField("Time", nil, []time.Time{ time.Date(2020, 1, 2, 3, 4, 20, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 21, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 22, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 23, 0, time.UTC), time.Date(2020, 1, 2, 3, 4, 24, 0, time.UTC), }), data.NewField("Values Ints", nil, []*int64{ pointer.Int64(12), nil, nil, nil, pointer.Int64(15), }), data.NewField(`Values Floats`, data.Labels{"Animal Factor": "sloth"}, []*float64{ pointer.Float64(12.5), nil, nil, nil, pointer.Float64(15.0), })), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { frame, err := resample(tt.input, dataQueryModel{ FillMissing: tt.fillMissing, TimeRange: tt.timeRange, Interval: tt.interval, }) require.NoError(t, err) if diff := cmp.Diff(tt.output, frame, data.FrameTestCompareOptions()...); diff != "" { t.Errorf("Result mismatch (-want +got):\n%s", diff) } }) } }
pkg/tsdb/sqleng/resample_test.go
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017598806880414486, 0.00017249182565137744, 0.0001598879898665473, 0.0001729957148199901, 0.0000030898772820364684 ]
{ "id": 2, "code_window": [ "import React, { memo, FC } from 'react';\n", "import { QueryEditorProps } from '@grafana/data';\n", "import { PrometheusDatasource } from '../datasource';\n", "import { PromQuery, PromOptions } from '../types';\n", "import PromQueryField from './PromQueryField';\n", "import { PromExploreExtraField } from './PromExploreExtraField';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, FC, useEffect } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 0 }
import React, { memo, useEffect, useCallback } from 'react'; import { usePrevious } from 'react-use'; import { isEqual } from 'lodash'; import { css, cx } from '@emotion/css'; import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui'; import { PromQuery } from '../types'; import { PromExemplarField } from './PromExemplarField'; import { PrometheusDatasource } from '../datasource'; export interface PromExploreExtraFieldProps { query: PromQuery; onChange: (value: PromQuery) => void; onRunQuery: () => void; datasource: PrometheusDatasource; } export const PromExploreExtraField: React.FC<PromExploreExtraFieldProps> = memo( ({ query, datasource, onChange, onRunQuery }) => { const rangeOptions = [ { value: 'range', label: 'Range', description: 'Run query over a range of time.' }, { value: 'instant', label: 'Instant', description: 'Run query against a single point in time. For this query, the "To" time is used.', }, { value: 'both', label: 'Both', description: 'Run an Instant query and a Range query.' }, ]; const prevQuery = usePrevious(query); // Setting default values useEffect(() => { if (query.exemplar === undefined) { onChange({ ...query, exemplar: true }); } if (!query.instant && !query.range) { onChange({ ...query, instant: true, range: true }); } }, [onChange, query]); const onExemplarChange = useCallback( (exemplar: boolean) => { if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) { onChange({ ...query, exemplar }); } }, [prevQuery, query, onChange] ); function onChangeQueryStep(interval: string) { onChange({ ...query, interval }); } function onStepChange(e: React.SyntheticEvent<HTMLInputElement>) { if (e.currentTarget.value !== query.interval) { onChangeQueryStep(e.currentTarget.value); } } function onReturnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) { if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey)) { onRunQuery(); } } function onQueryTypeChange(queryType: string) { let nextQuery; if (queryType === 'instant') { nextQuery = { ...query, instant: true, range: false }; } else if (queryType === 'range') { nextQuery = { ...query, instant: false, range: true }; } else { nextQuery = { ...query, instant: true, range: true }; } onChange(nextQuery); } return ( <div aria-label="Prometheus extra field" className="gf-form-inline"> {/*Query type field*/} <div data-testid="queryTypeField" className={cx( 'gf-form explore-input-margin', css` flex-wrap: nowrap; ` )} aria-label="Query type field" > <InlineFormLabel width="auto">Query type</InlineFormLabel> <RadioButtonGroup options={rangeOptions} value={query.range === query.instant ? 'both' : query.instant ? 'instant' : 'range'} onChange={onQueryTypeChange} /> </div> {/*Step field*/} <div data-testid="stepField" className={cx( 'gf-form', css` flex-wrap: nowrap; ` )} aria-label="Step field" > <InlineFormLabel width={5} tooltip={ 'Time units can be used here, for example: 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)' } > Step </InlineFormLabel> <input type={'text'} className="gf-form-input width-4" placeholder={'auto'} onChange={onStepChange} onKeyDown={onReturnKeyDown} value={query.interval ?? ''} /> </div> <PromExemplarField onChange={onExemplarChange} datasource={datasource} query={query} /> </div> ); } );
public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx
1
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.08309254795312881, 0.006878477055579424, 0.00016411517572123557, 0.00017338388715870678, 0.021312693133950233 ]
{ "id": 2, "code_window": [ "import React, { memo, FC } from 'react';\n", "import { QueryEditorProps } from '@grafana/data';\n", "import { PrometheusDatasource } from '../datasource';\n", "import { PromQuery, PromOptions } from '../types';\n", "import PromQueryField from './PromQueryField';\n", "import { PromExploreExtraField } from './PromExploreExtraField';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, FC, useEffect } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 0 }
import React, { memo } from 'react'; import { css, cx } from '@emotion/css'; import { GrafanaTheme2, TimeOption } from '@grafana/data'; import { useStyles2 } from '../../../themes/ThemeContext'; import { getFocusStyles } from '../../../themes/mixins'; import { v4 as uuidv4 } from 'uuid'; const getStyles = (theme: GrafanaTheme2) => { return { container: css` display: flex; align-items: center; flex-direction: row-reverse; justify-content: space-between; padding: 7px 9px 7px 9px; &:hover { background: ${theme.colors.action.hover}; cursor: pointer; } `, selected: css` background: ${theme.colors.action.selected}; font-weight: ${theme.typography.fontWeightMedium}; `, radio: css` opacity: 0; &:focus-visible + label { ${getFocusStyles(theme)}; } `, label: css` cursor: pointer; `, }; }; interface Props { value: TimeOption; selected?: boolean; onSelect: (option: TimeOption) => void; /** * Input identifier. This should be the same for all options in a group. */ name: string; } export const TimeRangeOption = memo<Props>(({ value, onSelect, selected = false, name }) => { const styles = useStyles2(getStyles); // In case there are more of the same timerange in the list const id = uuidv4(); return ( <li onClick={() => onSelect(value)} className={cx(styles.container, selected && styles.selected)}> <input className={styles.radio} checked={selected} name={name} type="checkbox" id={id} onChange={() => onSelect(value)} /> <label className={styles.label} htmlFor={id}> {value.display} </label> </li> ); }); TimeRangeOption.displayName = 'TimeRangeOption';
packages/grafana-ui/src/components/DateTimePickers/TimeRangePicker/TimeRangeOption.tsx
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.0003298255614936352, 0.00019686343148350716, 0.00016577032511122525, 0.00017638551071286201, 0.000051475039072101936 ]
{ "id": 2, "code_window": [ "import React, { memo, FC } from 'react';\n", "import { QueryEditorProps } from '@grafana/data';\n", "import { PrometheusDatasource } from '../datasource';\n", "import { PromQuery, PromOptions } from '../types';\n", "import PromQueryField from './PromQueryField';\n", "import { PromExploreExtraField } from './PromExploreExtraField';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, FC, useEffect } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 0 }
{ "__inputs": [], "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "7.3.0-pre" }, { "type": "panel", "id": "graph", "name": "Graph", "version": "" }, { "type": "datasource", "id": "stackdriver", "name": "Google Cloud Monitoring", "version": "1.0.0" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "gnetId": null, "graphTooltip": 0, "id": null, "links": [], "panels": [ { "datasource": null, "description": "", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "gridPos": { "h": 3, "w": 24, "x": 0, "y": 0 }, "id": 0, "options": { "mode": "markdown", "content": "This dashboard has 8 charts to display the metrics for the microservices in our [demo application](https://github.com/GoogleCloudPlatform/microservices-demo). The metrics include request count, response latencies, and request/response bytes." }, "pluginVersion": "7.4.0-pre", "timeFrom": null, "timeShift": null, "title": "MicroService Monitoring", "type": "text" }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 0 }, "hiddenSeries": false, "id": 1, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Server Request Count", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "k8s_container"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/server/request_count", "projectName": "$project", "unit": "1", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 0 }, "hiddenSeries": false, "id": 2, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Server Response Latencies", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_container"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/server/response_latencies", "projectName": "$project", "unit": "ms", "valueType": "DISTRIBUTION" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 8 }, "hiddenSeries": false, "id": 3, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Server Response Bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_container"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/server/response_bytes", "projectName": "$project", "unit": "By", "valueType": "DISTRIBUTION" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 8 }, "hiddenSeries": false, "id": 4, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Server Request Bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_container"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/server/request_bytes", "projectName": "$project", "unit": "By", "valueType": "DISTRIBUTION" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 16 }, "hiddenSeries": false, "id": 5, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Client Roundtrip Latencies", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_pod"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/client/roundtrip_latencies", "projectName": "$project", "unit": "ms", "valueType": "DISTRIBUTION" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 16 }, "hiddenSeries": false, "id": 6, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Client Request Count", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_RATE", "filters": ["resource.type", "=", "k8s_pod"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/client/request_count", "projectName": "$project", "unit": "1", "valueType": "INT64" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 24 }, "hiddenSeries": false, "id": 7, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Client Response Bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_pod"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/client/response_bytes", "projectName": "$project", "unit": "By", "valueType": "DISTRIBUTION" } } ] }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "$datasource", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "fill": 1, "fillGradient": 0, "gridPos": { "h": 8, "w": 12, "x": 12, "y": 24 }, "hiddenSeries": false, "id": 8, "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false, "sideWidth": 220 }, "lines": true, "linewidth": 1, "nullPointMode": "null", "options": { "alertThreshold": true }, "percentage": false, "pluginVersion": "7.4.0-pre", "pointradius": 2, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "thresholds": [], "timeFrom": null, "timeRegions": [], "timeShift": null, "title": "Client Request Bytes", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null }, "targets": [ { "queryType": "metrics", "refId": "A", "metricQuery": { "aliasBy": "", "alignmentPeriod": "$alignmentPeriod", "perSeriesAligner": "ALIGN_PERCENTILE_99", "filters": ["resource.type", "=", "k8s_pod"], "groupBys": [], "metricKind": "DELTA", "metricType": "istio.io/service/client/request_bytes", "projectName": "$project", "unit": "By", "valueType": "DISTRIBUTION" } } ] } ], "schemaVersion": 26, "style": "dark", "tags": ["Microservices", "Cloud Monitoring", "GCP"], "templating": { "list": [ { "current": {}, "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Datasource", "multi": false, "name": "datasource", "options": [], "query": "stackdriver", "queryValue": "", "refresh": 1, "regex": "", "skipUrlSync": false, "type": "datasource" }, { "allValue": null, "current": {}, "datasource": "$datasource", "definition": "Google Cloud Monitoring - Projects", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Project", "multi": false, "name": "project", "options": [], "query": { "labelKey": "", "loading": false, "projectName": "$project", "projects": [], "selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users", "selectedQueryType": "projects", "selectedSLOService": "", "selectedService": "actions.googleapis.com", "sloServices": [] }, "refresh": 1, "regex": "", "skipUrlSync": false, "sort": 0, "tagValuesQuery": "", "tags": [], "tagsQuery": "", "type": "query", "useTags": false }, { "allValue": null, "current": { "selected": false, "text": "grafana auto", "value": "grafana-auto" }, "datasource": "${datasource}", "definition": "", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Alignment Period", "multi": false, "name": "alignmentPeriod", "options": [ { "selected": true, "text": "grafana auto", "value": "grafana-auto" }, { "selected": false, "text": "stackdriver auto", "value": "stackdriver-auto" }, { "selected": false, "text": "cloud monitoring auto", "value": "cloud-monitoring-auto" }, { "selected": false, "text": "1m", "value": "+60s" }, { "selected": false, "text": "2m", "value": "+120s" }, { "selected": false, "text": "5m", "value": "+300s" }, { "selected": false, "text": "10m", "value": "+600s" }, { "selected": false, "text": "30m", "value": "+1800s" }, { "selected": false, "text": "1h", "value": "+3600s" }, { "selected": false, "text": "3h", "value": "+7200s" }, { "selected": false, "text": "6h", "value": "+21600s" }, { "selected": false, "text": "1d", "value": "+86400s" }, { "selected": false, "text": "3d", "value": "+259200s" }, { "selected": false, "text": "1w", "value": "+604800s" } ], "query": { "labelKey": "", "loading": false, "projectName": "$project", "projects": [ { "name": "project-1", "value": "project-1" }, { "name": "project-2", "value": "project-2" } ], "refId": "CloudMonitoringVariableQueryEditor-VariableQuery", "selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users", "selectedQueryType": "alignmentPeriods", "selectedSLOService": "", "selectedService": "actions.googleapis.com", "sloServices": [] }, "refresh": 0, "regex": "", "skipUrlSync": false, "sort": 0, "tagValuesQuery": "", "tags": [], "tagsQuery": "", "type": "query", "useTags": false } ] }, "time": { "from": "now-24h", "to": "now" }, "timepicker": {}, "timezone": "", "title": "MicroService Monitoring", "uid": "", "version": 5 }
public/app/plugins/datasource/cloud-monitoring/dashboards/micro-service-monitoring.json
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017960707191377878, 0.00017323202337138355, 0.00016578946087975055, 0.00017343804938718677, 0.000003000773858730099 ]
{ "id": 2, "code_window": [ "import React, { memo, FC } from 'react';\n", "import { QueryEditorProps } from '@grafana/data';\n", "import { PrometheusDatasource } from '../datasource';\n", "import { PromQuery, PromOptions } from '../types';\n", "import PromQueryField from './PromQueryField';\n", "import { PromExploreExtraField } from './PromExploreExtraField';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { memo, FC, useEffect } from 'react';\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "replace", "edit_start_line_idx": 0 }
/* ============================================================ SWITCH 3 - YES NO ============================================================ */ gf-form-switch[disabled] { .gf-form-switch, .gf-form-switch-container { cursor: default; pointer-events: none !important; .gf-form-label { color: $text-color-weak; } } } .gf-form-switch-container-react { display: flex; flex-shrink: 0; } .gf-form-switch-container { display: flex; cursor: pointer; margin-right: $space-xs; } .gf-form-switch { display: flex; position: relative; width: 56px; height: $input-height; background: $switch-bg; border: 1px solid $input-border-color; border-radius: $input-border-radius; align-items: center; justify-content: center; input { opacity: 0; width: 0; height: 0; } &--transparent { background: transparent; border: 0; width: 40px; } } /* The slider */ .gf-form-switch__slider { background: $switch-slider-off-bg; border-radius: 8px; height: 16px; width: 32px; display: block; position: relative; &::before { position: absolute; content: ''; height: 12px; width: 12px; left: 2px; top: 2px; background: $switch-slider-color; transition: 0.4s; border-radius: 50%; box-shadow: $switch-slider-shadow; } } input:checked + .gf-form-switch__slider { background: $switch-slider-on-bg; } input:checked + .gf-form-switch__slider::before { transform: translateX(16px); } .gf-form-checkbox { position: relative; display: flex; width: 50px; height: $input-height; background: $switch-bg; border: 1px solid $input-border-color; border-left: none; border-radius: $input-border-radius; align-items: center; justify-content: center; input { opacity: 0; width: 0; height: 0; appearance: none; } &--transparent { background: transparent; border: none; width: 23px; height: auto; position: relative; padding-left: 8px; } &--table-cell { width: 20px; background: transparent; height: auto; border: none; position: relative; top: -5px; } } .gf-form-switch__checkbox { height: 16px; width: 16px; border-radius: 3px; border: $checkbox-border; background: $checkbox-bg; display: flex; align-items: center; justify-content: center; } input:checked + .gf-form-switch__checkbox::before { font-family: 'FontAwesome'; content: '\f00c'; color: $checkbox-color; } input:checked + .gf-form-switch__checkbox { background: $checkbox-checked-bg; border: none; }
public/sass/components/_switch.scss
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017745504737831652, 0.00017494622443336993, 0.00016412769036833197, 0.00017629718058742583, 0.0000033753228763089282 ]
{ "id": 3, "code_window": [ "\n", "export const PromExploreQueryEditor: FC<Props> = (props: Props) => {\n", " const { range, query, data, datasource, history, onChange, onRunQuery } = props;\n", "\n", " return (\n", " <PromQueryField\n", " datasource={datasource}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Setting default values\n", " useEffect(() => {\n", " if (query.expr === undefined) {\n", " onChange({ ...query, expr: '' });\n", " }\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "add", "edit_start_line_idx": 12 }
import React, { memo, useEffect, useCallback } from 'react'; import { usePrevious } from 'react-use'; import { isEqual } from 'lodash'; import { css, cx } from '@emotion/css'; import { InlineFormLabel, RadioButtonGroup } from '@grafana/ui'; import { PromQuery } from '../types'; import { PromExemplarField } from './PromExemplarField'; import { PrometheusDatasource } from '../datasource'; export interface PromExploreExtraFieldProps { query: PromQuery; onChange: (value: PromQuery) => void; onRunQuery: () => void; datasource: PrometheusDatasource; } export const PromExploreExtraField: React.FC<PromExploreExtraFieldProps> = memo( ({ query, datasource, onChange, onRunQuery }) => { const rangeOptions = [ { value: 'range', label: 'Range', description: 'Run query over a range of time.' }, { value: 'instant', label: 'Instant', description: 'Run query against a single point in time. For this query, the "To" time is used.', }, { value: 'both', label: 'Both', description: 'Run an Instant query and a Range query.' }, ]; const prevQuery = usePrevious(query); // Setting default values useEffect(() => { if (query.exemplar === undefined) { onChange({ ...query, exemplar: true }); } if (!query.instant && !query.range) { onChange({ ...query, instant: true, range: true }); } }, [onChange, query]); const onExemplarChange = useCallback( (exemplar: boolean) => { if (!isEqual(query, prevQuery) || exemplar !== query.exemplar) { onChange({ ...query, exemplar }); } }, [prevQuery, query, onChange] ); function onChangeQueryStep(interval: string) { onChange({ ...query, interval }); } function onStepChange(e: React.SyntheticEvent<HTMLInputElement>) { if (e.currentTarget.value !== query.interval) { onChangeQueryStep(e.currentTarget.value); } } function onReturnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) { if (e.key === 'Enter' && (e.shiftKey || e.ctrlKey)) { onRunQuery(); } } function onQueryTypeChange(queryType: string) { let nextQuery; if (queryType === 'instant') { nextQuery = { ...query, instant: true, range: false }; } else if (queryType === 'range') { nextQuery = { ...query, instant: false, range: true }; } else { nextQuery = { ...query, instant: true, range: true }; } onChange(nextQuery); } return ( <div aria-label="Prometheus extra field" className="gf-form-inline"> {/*Query type field*/} <div data-testid="queryTypeField" className={cx( 'gf-form explore-input-margin', css` flex-wrap: nowrap; ` )} aria-label="Query type field" > <InlineFormLabel width="auto">Query type</InlineFormLabel> <RadioButtonGroup options={rangeOptions} value={query.range === query.instant ? 'both' : query.instant ? 'instant' : 'range'} onChange={onQueryTypeChange} /> </div> {/*Step field*/} <div data-testid="stepField" className={cx( 'gf-form', css` flex-wrap: nowrap; ` )} aria-label="Step field" > <InlineFormLabel width={5} tooltip={ 'Time units can be used here, for example: 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)' } > Step </InlineFormLabel> <input type={'text'} className="gf-form-input width-4" placeholder={'auto'} onChange={onStepChange} onKeyDown={onReturnKeyDown} value={query.interval ?? ''} /> </div> <PromExemplarField onChange={onExemplarChange} datasource={datasource} query={query} /> </div> ); } );
public/app/plugins/datasource/prometheus/components/PromExploreExtraField.tsx
1
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.996427595615387, 0.6359109282493591, 0.00017104475409723818, 0.9872074723243713, 0.47252169251441956 ]
{ "id": 3, "code_window": [ "\n", "export const PromExploreQueryEditor: FC<Props> = (props: Props) => {\n", " const { range, query, data, datasource, history, onChange, onRunQuery } = props;\n", "\n", " return (\n", " <PromQueryField\n", " datasource={datasource}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Setting default values\n", " useEffect(() => {\n", " if (query.expr === undefined) {\n", " onChange({ ...query, expr: '' });\n", " }\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "add", "edit_start_line_idx": 12 }
import { AlertmanagerGroup, AlertState } from 'app/plugins/datasource/alertmanager/types'; import React, { useState, useEffect } from 'react'; import { GrafanaTheme2, intervalToAbbreviatedDurationString } from '@grafana/data'; import { useStyles2, LinkButton } from '@grafana/ui'; import { css } from '@emotion/css'; import { AlertLabels } from 'app/features/alerting/unified/components/AlertLabels'; import { AlertGroupHeader } from 'app/features/alerting/unified/components/alert-groups/AlertGroupHeader'; import { CollapseToggle } from 'app/features/alerting/unified/components/CollapseToggle'; import { getNotificationsTextColors } from 'app/features/alerting/unified/styles/notifications'; import { makeAMLink } from 'app/features/alerting/unified/utils/misc'; import { getMatcherQueryParams } from 'app/features/alerting/unified/utils/matchers'; type Props = { alertManagerSourceName: string; group: AlertmanagerGroup; expandAll: boolean; }; export const AlertGroup = ({ alertManagerSourceName, group, expandAll }: Props) => { const [showAlerts, setShowAlerts] = useState(expandAll); const styles = useStyles2(getStyles); const textStyles = useStyles2(getNotificationsTextColors); useEffect(() => setShowAlerts(expandAll), [expandAll]); return ( <div className={styles.group} data-testid="alert-group"> {Object.keys(group.labels).length > 0 ? ( <AlertLabels labels={group.labels} /> ) : ( <div className={styles.noGroupingText}>No grouping</div> )} <div className={styles.row}> <CollapseToggle isCollapsed={!showAlerts} onToggle={() => setShowAlerts(!showAlerts)} />{' '} <AlertGroupHeader group={group} /> </div> {showAlerts && ( <div className={styles.alerts}> {group.alerts.map((alert, index) => { const state = alert.status.state.toUpperCase(); const interval = intervalToAbbreviatedDurationString({ start: new Date(alert.startsAt), end: Date.now(), }); return ( <div data-testid={'alert-group-alert'} className={styles.alert} key={`${alert.fingerprint}-${index}`}> <div> <span className={textStyles[alert.status.state]}>{state} </span>for {interval} </div> <div> <AlertLabels labels={alert.labels} /> </div> <div className={styles.actionsRow}> {alert.status.state === AlertState.Suppressed && ( <LinkButton href={`${makeAMLink( '/alerting/silences', alertManagerSourceName )}&silenceIds=${alert.status.silencedBy.join(',')}`} className={styles.button} icon={'bell'} size={'sm'} > Manage silences </LinkButton> )} {alert.status.state === AlertState.Active && ( <LinkButton href={`${makeAMLink('/alerting/silence/new', alertManagerSourceName)}&${getMatcherQueryParams( alert.labels )}`} className={styles.button} icon={'bell-slash'} size={'sm'} > Silence </LinkButton> )} {alert.generatorURL && ( <LinkButton className={styles.button} href={alert.generatorURL} icon={'chart-line'} size={'sm'}> See source </LinkButton> )} </div> </div> ); })} </div> )} </div> ); }; const getStyles = (theme: GrafanaTheme2) => ({ noGroupingText: css` height: ${theme.spacing(4)}; `, group: css` background-color: ${theme.colors.background.secondary}; margin: ${theme.spacing(0.5, 1, 0.5, 1)}; padding: ${theme.spacing(1)}; `, row: css` display: flex; flex-direction: row; align-items: center; `, alerts: css` margin: ${theme.spacing(0, 2, 0, 4)}; `, alert: css` padding: ${theme.spacing(1, 0)}; & + & { border-top: 1px solid ${theme.colors.border.medium}; } `, button: css` & + & { margin-left: ${theme.spacing(1)}; } `, actionsRow: css` padding: ${theme.spacing(1, 0)}; `, });
public/app/plugins/panel/alertGroups/AlertGroup.tsx
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.0005874097696505487, 0.00020602522999979556, 0.0001712647353997454, 0.00017345100059174, 0.00011011966853402555 ]
{ "id": 3, "code_window": [ "\n", "export const PromExploreQueryEditor: FC<Props> = (props: Props) => {\n", " const { range, query, data, datasource, history, onChange, onRunQuery } = props;\n", "\n", " return (\n", " <PromQueryField\n", " datasource={datasource}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Setting default values\n", " useEffect(() => {\n", " if (query.expr === undefined) {\n", " onChange({ ...query, expr: '' });\n", " }\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "add", "edit_start_line_idx": 12 }
+++ title = "Configure Grafana Live" description = "Grafana Live configuration guide" keywords = ["Grafana", "live", "guide", "websocket"] weight = 120 +++ # Configure Grafana Live Grafana Live is enabled by default. In Grafana v8.0, it has a strict default for a maximum number of connections per Grafana server instance. ## Max number of connections Grafana Live uses persistent connections (WebSocket at the moment) to deliver real-time updates to clients. WebSocket is a persistent connection that starts with an HTTP Upgrade request (using the same HTTP port as the rest of Grafana) and then switches to a TCP mode where WebSocket frames can travel in both directions between a client and a server. Each logged-in user opens a WebSocket connection – one per browser tab. The number of maximum WebSocket connections users can establish with Grafana is limited to 100 by default. See [max_connections]({{< relref "../administration/configuration.md#max_connections" >}}) option. In case you want to increase this limit, ensure that your server and infrastructure allow handling more connections. The following sections discuss several common problems which could happen when managing persistent connections, in particular WebSocket connections. ## Request origin check To avoid hijacking of WebSocket connection Grafana Live checks the Origin request header sent by a client in an HTTP Upgrade request. Requests without Origin header pass through without any origin check. By default, Live accepts connections with Origin header that matches configured [root_url]({{< relref "../administration/configuration.md#root_url" >}}) (which is a public Grafana URL). It is possible to provide a list of additional origin patterns to allow WebSocket connections from. This can be achieved using the [allowed_origins]({{< relref "../administration/configuration.md#allowed_origins" >}}) option of Grafana Live configuration. ### Resource usage Each persistent connection costs some memory on a server. Typically, this should be about 50 KB per connection at this moment. Thus a server with 1 GB RAM is expected to handle about 20k connections max. Each active connection consumes additional CPU resources since the client and server send PING/PONG frames to each other to maintain a connection. Using the streaming functionality results in additional CPU usage. The exact CPU resource utilization can be hard to estimate as it heavily depends on the Grafana Live usage pattern. ### Open file limit Each WebSocket connection costs a file descriptor on a server machine where Grafana runs. Most operating systems have a quite low default limit for the maximum number of descriptors that process can open. To look at the current limit on Unix run: ``` ulimit -n ``` On a Linux system, you can also check out the current limits for a running process with: ``` cat /proc/<PROCESS_PID>/limits ``` The open files limit shows approximately how many user connections your server can currently handle. To increase this limit, refer to [these instructions](https://docs.riak.com/riak/kv/2.2.3/using/performance/open-files-limit.1.html)for popular operating systems. ### Ephemeral port exhaustion Ephemeral port exhaustion problem can happen between your load balancer (or reverse proxy) software and Grafana server. For example, when you load balance requests/connections between different Grafana instances. If you connect directly to a single Grafana server instance, then you should not come across this issue. The problem arises because each TCP connection uniquely identified in the OS by the 4-part-tuple: ``` source ip | source port | destination ip | destination port ``` By default, on load balancer/server boundary you are limited to 65535 possible variants. But actually, due to some OS limits (for example on Unix available ports defined in `ip_local_port_range` sysctl parameter) and sockets in TIME_WAIT state, the number is even less. In order to eliminate a problem you can: - Increase the ephemeral port range by tuning `ip_local_port_range` kernel option. - Deploy more Grafana server instances to load balance across. - Deploy more load balancer instances. - Use virtual network interfaces. ### WebSocket and proxies Not all proxies can transparently proxy WebSocket connections by default. For example, if you are using Nginx before Grafana you need to configure WebSocket proxy like this: ``` http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream grafana { server 127.0.0.1:3000; } server { listen 8000; location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $http_host; proxy_pass http://grafana; } } } ``` See the [Nginx blog on their website](https://www.nginx.com/blog/websocket-nginx/) for more information. Also, refer to your load balancer/reverse proxy documentation to find out more information on dealing with WebSocket connections. Some corporate proxies can remove headers required to properly establish a WebSocket connection. In this case, you should tune intermediate proxies to not remove required headers. However, the better option is to use Grafana with TLS. Now WebSocket connection will inherit TLS and thus must be handled transparently by proxies. Proxies like Nginx and Envoy have default limits on maximum number of connections which can be established. Make sure you have a reasonable limit for max number of incoming and outgoing connections in your proxy configuration.
docs/sources/live/configure-grafana-live.md
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00019569876894820482, 0.0001722619927022606, 0.00016355996194761246, 0.00016941236390266567, 0.00000844715759740211 ]
{ "id": 3, "code_window": [ "\n", "export const PromExploreQueryEditor: FC<Props> = (props: Props) => {\n", " const { range, query, data, datasource, history, onChange, onRunQuery } = props;\n", "\n", " return (\n", " <PromQueryField\n", " datasource={datasource}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Setting default values\n", " useEffect(() => {\n", " if (query.expr === undefined) {\n", " onChange({ ...query, expr: '' });\n", " }\n", " if (query.exemplar === undefined) {\n", " onChange({ ...query, exemplar: true });\n", " }\n", "\n", " if (!query.instant && !query.range) {\n", " onChange({ ...query, instant: true, range: true });\n", " }\n", " }, [onChange, query]);\n", "\n" ], "file_path": "public/app/plugins/datasource/prometheus/components/PromExploreQueryEditor.tsx", "type": "add", "edit_start_line_idx": 12 }
{{Subject .Subject "Reset your Grafana password - {{.Name}}"}} Hi {{.Name}}, Copy and paste the following link directly in your browser to reset your password within {{.EmailCodeValidHours}} hours. {{.AppUrl}}user/password/reset?code={{.Code}} Sent by Grafana v{{.BuildVersion}} (c) 2021 Grafana Labs
public/emails/reset_password.txt
0
https://github.com/grafana/grafana/commit/fd1b0de34b35adebb1d4c158bf585e7c03d79a65
[ 0.00017377050244249403, 0.00017377050244249403, 0.00017377050244249403, 0.00017377050244249403, 0 ]
{ "id": 0, "code_window": [ "import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';\n", "\n", "// --- adapter\n", "\n", "class OutlineAdapter {\n", "\n", "\tprivate _documents: ExtHostDocuments;\n", "\tprivate _provider: vscode.DocumentSymbolProvider;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "class DocumentSymbolAdapter {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 31 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9992204904556274, 0.06909434497356415, 0.00016758512356318533, 0.0023496958892792463, 0.2175392210483551 ]
{ "id": 0, "code_window": [ "import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';\n", "\n", "// --- adapter\n", "\n", "class OutlineAdapter {\n", "\n", "\tprivate _documents: ExtHostDocuments;\n", "\tprivate _provider: vscode.DocumentSymbolProvider;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "class DocumentSymbolAdapter {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 31 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export const typescript = 'typescript'; export const typescriptreact = 'typescriptreact'; export const javascript = 'javascript'; export const javascriptreact = 'javascriptreact'; export const jsxTags = 'jsx-tags'; export function isSupportedLanguageMode(doc: vscode.TextDocument) { return vscode.languages.match([typescript, typescriptreact, javascript, javascriptreact], doc) > 0; } export function isTypeScriptDocument(doc: vscode.TextDocument) { return vscode.languages.match([typescript, typescriptreact], doc) > 0; }
extensions/typescript-language-features/src/utils/languageModeIds.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00022228491434361786, 0.00018961273599416018, 0.00017278050654567778, 0.00017377280164510012, 0.00002310626587131992 ]
{ "id": 0, "code_window": [ "import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';\n", "\n", "// --- adapter\n", "\n", "class OutlineAdapter {\n", "\n", "\tprivate _documents: ExtHostDocuments;\n", "\tprivate _provider: vscode.DocumentSymbolProvider;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "class DocumentSymbolAdapter {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 31 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="-2 -2 16 16" enable-background="new -2 -2 16 16"><polygon fill="#424242" points="9,0 4.5,9 3,6 0,6 3,12 6,12 12,0"/></svg>
src/vs/workbench/parts/files/electron-browser/media/check.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017044042760971934, 0.00017044042760971934, 0.00017044042760971934, 0.00017044042760971934, 0 ]
{ "id": 0, "code_window": [ "import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';\n", "\n", "// --- adapter\n", "\n", "class OutlineAdapter {\n", "\n", "\tprivate _documents: ExtHostDocuments;\n", "\tprivate _provider: vscode.DocumentSymbolProvider;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "class DocumentSymbolAdapter {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 31 }
/*--------------------------------------------------------------------------------------------- * 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 vscode from 'vscode'; suite('Configuration tests', () => { test('configurations, language defaults', function () { const defaultLanguageSettings = vscode.workspace.getConfiguration().get('[abcLang]'); assert.deepEqual(defaultLanguageSettings, { 'editor.lineNumbers': 'off', 'editor.tabSize': 2 }); }); test('configuration, defaults', () => { const config = vscode.workspace.getConfiguration('farboo'); assert.ok(config.has('config0')); assert.equal(config.get('config0'), true); assert.equal(config.get('config4'), ''); assert.equal(config['config0'], true); assert.equal(config['config4'], ''); assert.throws(() => (<any>config)['config4'] = 'valuevalue'); assert.ok(config.has('nested.config1')); assert.equal(config.get('nested.config1'), 42); assert.ok(config.has('nested.config2')); assert.equal(config.get('nested.config2'), 'Das Pferd frisst kein Reis.'); }); test('configuration, name vs property', () => { const config = vscode.workspace.getConfiguration('farboo'); assert.ok(config.has('get')); assert.equal(config.get('get'), 'get-prop'); assert.deepEqual(config['get'], config.get); assert.throws(() => config['get'] = <any>'get-prop'); }); });
extensions/vscode-api-tests/src/singlefolder-tests/configuration.test.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00025806104531511664, 0.00019278915715403855, 0.00016888930986169726, 0.00017375491734128445, 0.00003338349415571429 ]
{ "id": 1, "code_window": [ "\t\treturn asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => {\n", "\t\t\tif (isFalsyOrEmpty(value)) {\n", "\t\t\t\treturn undefined;\n", "\t\t\t}\n", "\t\t\tif (value[0] instanceof DocumentSymbol) {\n", "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t} else if (value[0] instanceof DocumentSymbol) {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 46 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9953951239585876, 0.008496453054249287, 0.00016284242155961692, 0.00018470370559953153, 0.08465278148651123 ]
{ "id": 1, "code_window": [ "\t\treturn asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => {\n", "\t\t\tif (isFalsyOrEmpty(value)) {\n", "\t\t\t\treturn undefined;\n", "\t\t\t}\n", "\t\t\tif (value[0] instanceof DocumentSymbol) {\n", "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t} else if (value[0] instanceof DocumentSymbol) {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 46 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#252526}.icon-vs-out{fill:#252526}.icon-vs-bg{fill:#c5c5c5}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M9 15v-3H7v3H4v-3H1V9h3V7H1V4h3V1h3v3h2V1h3v3h3v3h-3v2h3v3h-3v3H9z" id="outline"/><g id="iconBg"><path class="icon-vs-bg" d="M14 6V5h-3V2h-1v3H6V2H5v3H2v1h3v4H2v1h3v3h1v-3h4v3h1v-3h3v-1h-3V6h3zm-4 4H6V6h4v4z"/></g></svg>
src/vs/editor/contrib/documentSymbols/media/Numeric_16x_darkp.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017440822557546198, 0.00017440822557546198, 0.00017440822557546198, 0.00017440822557546198, 0 ]
{ "id": 1, "code_window": [ "\t\treturn asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => {\n", "\t\t\tif (isFalsyOrEmpty(value)) {\n", "\t\t\t\treturn undefined;\n", "\t\t\t}\n", "\t\t\tif (value[0] instanceof DocumentSymbol) {\n", "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t} else if (value[0] instanceof DocumentSymbol) {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 46 }
{ "comments": { "blockComment": [ "<!--", "-->" ] }, "brackets": [ ["<!--", "-->"], ["<", ">"], ["{", "}"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}"}, { "open": "[", "close": "]"}, { "open": "(", "close": ")" }, { "open": "'", "close": "'" }, { "open": "\"", "close": "\"" } ], "surroundingPairs": [ { "open": "'", "close": "'" }, { "open": "\"", "close": "\"" }, { "open": "<", "close": ">" } ] }
extensions/razor/language-configuration.json
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.000173858818016015, 0.0001720598229439929, 0.00017043326806742698, 0.000171887397300452, 0.0000014037799473953783 ]
{ "id": 1, "code_window": [ "\t\treturn asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => {\n", "\t\t\tif (isFalsyOrEmpty(value)) {\n", "\t\t\t\treturn undefined;\n", "\t\t\t}\n", "\t\t\tif (value[0] instanceof DocumentSymbol) {\n", "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t} else if (value[0] instanceof DocumentSymbol) {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 46 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-fg{fill:#f0eff1}.icon-vs-action-orange{fill:#c27d1a}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M14.414 1L16 2.586v5.828L14.414 10H10v3.416L8.414 15H1.586L0 13.416v-5.83L1.586 6H6V2.586L7.586 1h6.828z" id="outline"/><path class="icon-vs-fg" d="M2 13h6V8H2v5zm1-4h4v1H3V9zm0 2h4v1H3v-1zm11-5V3H8v3h.414L9 6.586V6h4v1H9.414l.586.586V8h4V6zm-1-1H9V4h4v1z" id="iconFg"/><path class="icon-vs-action-orange" d="M3 11h4.001v1H3v-1zm0-1h4.001V9H3v1zm6-2v5l-1 1H2l-1-1V8l1-1h6l1 1zM8 8H2v5h6V8zm1-2l1 1h3V6H9zm0-1h4V4H9v1zm5-3H8L7 3v3h1V3h6v5h-4v1h4l1-1V3l-1-1z" id="iconBg"/></svg>
src/vs/editor/contrib/suggest/media/Enumerator_16x.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0001721145526971668, 0.0001721145526971668, 0.0001721145526971668, 0.0001721145526971668, 0 ]
{ "id": 2, "code_window": [ "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n", "\t\t\t\treturn OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value);\n", "\t\t\t}\n", "\t\t});\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn DocumentSymbolAdapter._asDocumentSymbolTree(<SymbolInformation[]>value);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.03519587218761444, 0.0006073129479773343, 0.00015869233175180852, 0.00017249753000214696, 0.003012928646057844 ]
{ "id": 2, "code_window": [ "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n", "\t\t\t\treturn OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value);\n", "\t\t\t}\n", "\t\t});\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn DocumentSymbolAdapter._asDocumentSymbolTree(<SymbolInformation[]>value);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace } from 'vscode'; import { IJSONContribution, ISuggestionsCollector } from './jsonContributions'; import { XHRRequest } from 'request-light'; import { Location } from 'jsonc-parser'; import { textToMarkedString } from './markedTextUtil'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const USER_AGENT = 'Visual Studio Code'; export class BowerJSONContribution implements IJSONContribution { private topRanked = ['twitter', 'bootstrap', 'angular-1.1.6', 'angular-latest', 'angulerjs', 'd3', 'myjquery', 'jq', 'abcdef1234567890', 'jQuery', 'jquery-1.11.1', 'jquery', 'sushi-vanilla-x-data', 'font-awsome', 'Font-Awesome', 'font-awesome', 'fontawesome', 'html5-boilerplate', 'impress.js', 'homebrew', 'backbone', 'moment1', 'momentjs', 'moment', 'linux', 'animate.css', 'animate-css', 'reveal.js', 'jquery-file-upload', 'blueimp-file-upload', 'threejs', 'express', 'chosen', 'normalize-css', 'normalize.css', 'semantic', 'semantic-ui', 'Semantic-UI', 'modernizr', 'underscore', 'underscore1', 'material-design-icons', 'ionic', 'chartjs', 'Chart.js', 'nnnick-chartjs', 'select2-ng', 'select2-dist', 'phantom', 'skrollr', 'scrollr', 'less.js', 'leancss', 'parser-lib', 'hui', 'bootstrap-languages', 'async', 'gulp', 'jquery-pjax', 'coffeescript', 'hammer.js', 'ace', 'leaflet', 'jquery-mobile', 'sweetalert', 'typeahead.js', 'soup', 'typehead.js', 'sails', 'codeigniter2']; private xhr: XHRRequest; public constructor(xhr: XHRRequest) { this.xhr = xhr; } public getDocumentSelector(): DocumentSelector { return [{ language: 'json', scheme: '*', pattern: '**/bower.json' }, { language: 'json', scheme: '*', pattern: '**/.bower.json' }]; } private onlineEnabled() { return !!workspace.getConfiguration('npm').get('fetchOnlinePackageInfo'); } public collectDefaultSuggestions(_resource: string, collector: ISuggestionsCollector): Thenable<any> { const defaultValue = { 'name': '${1:name}', 'description': '${2:description}', 'authors': ['${3:author}'], 'version': '${4:1.0.0}', 'main': '${5:pathToMain}', 'dependencies': {} }; const proposal = new CompletionItem(localize('json.bower.default', 'Default bower.json')); proposal.kind = CompletionItemKind.Class; proposal.insertText = new SnippetString(JSON.stringify(defaultValue, null, '\t')); collector.add(proposal); return Promise.resolve(null); } public collectPropertySuggestions(_resource: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> | null { if ((location.matches(['dependencies']) || location.matches(['devDependencies']))) { if (currentWord.length > 0 && this.onlineEnabled()) { const queryUrl = 'https://registry.bower.io/packages/search/' + encodeURIComponent(currentWord); return this.xhr({ url: queryUrl, agent: USER_AGENT }).then((success) => { if (success.status === 200) { try { const obj = JSON.parse(success.responseText); if (Array.isArray(obj)) { const results = <{ name: string; description: string; }[]>obj; for (const result of results) { const name = result.name; const description = result.description || ''; const insertText = new SnippetString().appendText(JSON.stringify(name)); if (addValue) { insertText.appendText(': ').appendPlaceholder('latest'); if (!isLast) { insertText.appendText(','); } } const proposal = new CompletionItem(name); proposal.kind = CompletionItemKind.Property; proposal.insertText = insertText; proposal.filterText = JSON.stringify(name); proposal.documentation = description; collector.add(proposal); } collector.setAsIncomplete(); } } catch (e) { // ignore } } else { collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', success.responseText)); return 0; } return undefined; }, (error) => { collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', error.responseText)); return 0; }); } else { this.topRanked.forEach((name) => { const insertText = new SnippetString().appendText(JSON.stringify(name)); if (addValue) { insertText.appendText(': ').appendPlaceholder('latest'); if (!isLast) { insertText.appendText(','); } } const proposal = new CompletionItem(name); proposal.kind = CompletionItemKind.Property; proposal.insertText = insertText; proposal.filterText = JSON.stringify(name); proposal.documentation = ''; collector.add(proposal); }); collector.setAsIncomplete(); return Promise.resolve(null); } } return null; } public collectValueSuggestions(_resource: string, location: Location, collector: ISuggestionsCollector): Thenable<any> { if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) { // not implemented. Could be do done calling the bower command. Waiting for web API: https://github.com/bower/registry/issues/26 const proposal = new CompletionItem(localize('json.bower.latest.version', 'latest')); proposal.insertText = new SnippetString('"${1:latest}"'); proposal.filterText = '""'; proposal.kind = CompletionItemKind.Value; proposal.documentation = 'The latest version of the package'; collector.add(proposal); } return Promise.resolve(null); } public resolveSuggestion(item: CompletionItem): Thenable<CompletionItem | null> | null { if (item.kind === CompletionItemKind.Property && item.documentation === '') { return this.getInfo(item.label).then(documentation => { if (documentation) { item.documentation = documentation; return item; } return null; }); } return null; } private getInfo(pack: string): Thenable<string | undefined> { if (!this.onlineEnabled()) { return Promise.resolve(undefined); } const queryUrl = 'https://registry.bower.io/packages/' + encodeURIComponent(pack); return this.xhr({ url: queryUrl, agent: USER_AGENT }).then((success) => { try { const obj = JSON.parse(success.responseText); if (obj && obj.url) { let url: string = obj.url; if (url.indexOf('git://') === 0) { url = url.substring(6); } if (url.lastIndexOf('.git') === url.length - 4) { url = url.substring(0, url.length - 4); } return url; } } catch (e) { // ignore } return undefined; }, () => { return undefined; }); } public getInfoContribution(_resource: string, location: Location): Thenable<MarkedString[] | null> | null { if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) { const pack = location.path[location.path.length - 1]; if (typeof pack === 'string') { return this.getInfo(pack).then(documentation => { if (documentation) { return [textToMarkedString(documentation)]; } return null; }); } } return null; } }
extensions/npm/src/features/bowerJSONContribution.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017796932661440223, 0.00017253788246307522, 0.000167720383615233, 0.00017200394358951598, 0.000002846779352694284 ]
{ "id": 2, "code_window": [ "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n", "\t\t\t\treturn OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value);\n", "\t\t\t}\n", "\t\t});\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn DocumentSymbolAdapter._asDocumentSymbolTree(<SymbolInformation[]>value);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 50 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out", "experimentalDecorators": true }, "include": [ "src/**/*" ] }
extensions/typescript-language-features/tsconfig.json
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0001784144842531532, 0.00017575414676684886, 0.00017309380928054452, 0.00017575414676684886, 0.0000026603374863043427 ]
{ "id": 2, "code_window": [ "\t\t\t\treturn (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from);\n", "\t\t\t} else {\n", "\t\t\t\treturn OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value);\n", "\t\t\t}\n", "\t\t});\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn DocumentSymbolAdapter._asDocumentSymbolTree(<SymbolInformation[]>value);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { toUint32 } from 'vs/editor/common/core/uint'; export class PrefixSumIndexOfResult { _prefixSumIndexOfResultBrand: void; index: number; remainder: number; constructor(index: number, remainder: number) { this.index = index; this.remainder = remainder; } } export class PrefixSumComputer { /** * values[i] is the value at index i */ private values: Uint32Array; /** * prefixSum[i] = SUM(heights[j]), 0 <= j <= i */ private prefixSum: Uint32Array; /** * prefixSum[i], 0 <= i <= prefixSumValidIndex can be trusted */ private prefixSumValidIndex: Int32Array; constructor(values: Uint32Array) { this.values = values; this.prefixSum = new Uint32Array(values.length); this.prefixSumValidIndex = new Int32Array(1); this.prefixSumValidIndex[0] = -1; } public getCount(): number { return this.values.length; } public insertValues(insertIndex: number, insertValues: Uint32Array): boolean { insertIndex = toUint32(insertIndex); const oldValues = this.values; const oldPrefixSum = this.prefixSum; const insertValuesLen = insertValues.length; if (insertValuesLen === 0) { return false; } this.values = new Uint32Array(oldValues.length + insertValuesLen); this.values.set(oldValues.subarray(0, insertIndex), 0); this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen); this.values.set(insertValues, insertIndex); if (insertIndex - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = insertIndex - 1; } this.prefixSum = new Uint32Array(this.values.length); if (this.prefixSumValidIndex[0] >= 0) { this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1)); } return true; } public changeValue(index: number, value: number): boolean { index = toUint32(index); value = toUint32(value); if (this.values[index] === value) { return false; } this.values[index] = value; if (index - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = index - 1; } return true; } public removeValues(startIndex: number, cnt: number): boolean { startIndex = toUint32(startIndex); cnt = toUint32(cnt); const oldValues = this.values; const oldPrefixSum = this.prefixSum; if (startIndex >= oldValues.length) { return false; } let maxCnt = oldValues.length - startIndex; if (cnt >= maxCnt) { cnt = maxCnt; } if (cnt === 0) { return false; } this.values = new Uint32Array(oldValues.length - cnt); this.values.set(oldValues.subarray(0, startIndex), 0); this.values.set(oldValues.subarray(startIndex + cnt), startIndex); this.prefixSum = new Uint32Array(this.values.length); if (startIndex - 1 < this.prefixSumValidIndex[0]) { this.prefixSumValidIndex[0] = startIndex - 1; } if (this.prefixSumValidIndex[0] >= 0) { this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1)); } return true; } public getTotalValue(): number { if (this.values.length === 0) { return 0; } return this._getAccumulatedValue(this.values.length - 1); } public getAccumulatedValue(index: number): number { if (index < 0) { return 0; } index = toUint32(index); return this._getAccumulatedValue(index); } private _getAccumulatedValue(index: number): number { if (index <= this.prefixSumValidIndex[0]) { return this.prefixSum[index]; } let startIndex = this.prefixSumValidIndex[0] + 1; if (startIndex === 0) { this.prefixSum[0] = this.values[0]; startIndex++; } if (index >= this.values.length) { index = this.values.length - 1; } for (let i = startIndex; i <= index; i++) { this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i]; } this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index); return this.prefixSum[index]; } public getIndexOf(accumulatedValue: number): PrefixSumIndexOfResult { accumulatedValue = Math.floor(accumulatedValue); //@perf // Compute all sums (to get a fully valid prefixSum) this.getTotalValue(); let low = 0; let high = this.values.length - 1; let mid = 0; let midStop = 0; let midStart = 0; while (low <= high) { mid = low + ((high - low) / 2) | 0; midStop = this.prefixSum[mid]; midStart = midStop - this.values[mid]; if (accumulatedValue < midStart) { high = mid - 1; } else if (accumulatedValue >= midStop) { low = mid + 1; } else { break; } } return new PrefixSumIndexOfResult(mid, accumulatedValue - midStart); } } export class PrefixSumComputerWithCache { private readonly _actual: PrefixSumComputer; private _cacheAccumulatedValueStart: number = 0; private _cache: PrefixSumIndexOfResult[] | null = null; constructor(values: Uint32Array) { this._actual = new PrefixSumComputer(values); this._bustCache(); } private _bustCache(): void { this._cacheAccumulatedValueStart = 0; this._cache = null; } public insertValues(insertIndex: number, insertValues: Uint32Array): void { if (this._actual.insertValues(insertIndex, insertValues)) { this._bustCache(); } } public changeValue(index: number, value: number): void { if (this._actual.changeValue(index, value)) { this._bustCache(); } } public removeValues(startIndex: number, cnt: number): void { if (this._actual.removeValues(startIndex, cnt)) { this._bustCache(); } } public getTotalValue(): number { return this._actual.getTotalValue(); } public getAccumulatedValue(index: number): number { return this._actual.getAccumulatedValue(index); } public getIndexOf(accumulatedValue: number): PrefixSumIndexOfResult { accumulatedValue = Math.floor(accumulatedValue); //@perf if (this._cache !== null) { let cacheIndex = accumulatedValue - this._cacheAccumulatedValueStart; if (cacheIndex >= 0 && cacheIndex < this._cache.length) { // Cache hit! return this._cache[cacheIndex]; } } // Cache miss! return this._actual.getIndexOf(accumulatedValue); } /** * Gives a hint that a lot of requests are about to come in for these accumulated values. */ public warmUpCache(accumulatedValueStart: number, accumulatedValueEnd: number): void { let newCache: PrefixSumIndexOfResult[] = []; for (let accumulatedValue = accumulatedValueStart; accumulatedValue <= accumulatedValueEnd; accumulatedValue++) { newCache[accumulatedValue - accumulatedValueStart] = this.getIndexOf(accumulatedValue); } this._cache = newCache; this._cacheAccumulatedValueStart = accumulatedValueStart; } }
src/vs/editor/common/viewModel/prefixSumComputer.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00032304110936820507, 0.00018082131282426417, 0.00016219652025029063, 0.00017236922576557845, 0.00003320015093777329 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tprivate static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] {\n", "\t\t// first sort by start (and end) and then loop over all elements\n", "\t\t// and build a tree based on containment.\n", "\t\tinfos = infos.slice(0).sort((a, b) => {\n", "\t\t\tlet res = a.location.range.start.compareTo(b.location.range.start);\n", "\t\t\tif (res === 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _asDocumentSymbolTree(infos: SymbolInformation[]): modes.DocumentSymbol[] {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9983134269714355, 0.028656426817178726, 0.00016223193961195648, 0.00017004547407850623, 0.1639624685049057 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tprivate static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] {\n", "\t\t// first sort by start (and end) and then loop over all elements\n", "\t\t// and build a tree based on containment.\n", "\t\tinfos = infos.slice(0).sort((a, b) => {\n", "\t\t\tlet res = a.location.range.start.compareTo(b.location.range.start);\n", "\t\t\tif (res === 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _asDocumentSymbolTree(infos: SymbolInformation[]): modes.DocumentSymbol[] {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 55 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="-1 -3 16 16" enable-background="new -1 -3 16 16"><polygon fill="#C5C5C5" points="13,4 6,4 9,1 6,1 2,5 6,9 9,9 6,6 13,6"/></svg>
src/vs/workbench/browser/parts/editor/media/previous-diff-inverse.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017301557818427682, 0.00017301557818427682, 0.00017301557818427682, 0.00017301557818427682, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tprivate static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] {\n", "\t\t// first sort by start (and end) and then loop over all elements\n", "\t\t// and build a tree based on containment.\n", "\t\tinfos = infos.slice(0).sort((a, b) => {\n", "\t\t\tlet res = a.location.range.start.compareTo(b.location.range.start);\n", "\t\t\tif (res === 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _asDocumentSymbolTree(infos: SymbolInformation[]): modes.DocumentSymbol[] {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { onUnexpectedError } from 'vs/base/common/errors'; import { ConfigurationModelParser, ConfigurationModel } from 'vs/platform/configuration/common/configurationModels'; import { ConfigWatcher } from 'vs/base/node/config'; import { Event, Emitter } from 'vs/base/common/event'; export class UserConfiguration extends Disposable { private userConfigModelWatcher: ConfigWatcher<ConfigurationModelParser>; private initializePromise: Promise<void>; private readonly _onDidChangeConfiguration: Emitter<ConfigurationModel> = this._register(new Emitter<ConfigurationModel>()); readonly onDidChangeConfiguration: Event<ConfigurationModel> = this._onDidChangeConfiguration.event; constructor(private settingsPath: string) { super(); } initialize(): Promise<ConfigurationModel> { if (!this.initializePromise) { this.initializePromise = new Promise<void>((c, e) => { this.userConfigModelWatcher = new ConfigWatcher(this.settingsPath, { changeBufferDelay: 300, onError: error => onUnexpectedError(error), defaultConfig: new ConfigurationModelParser(this.settingsPath), parse: (content: string, parseErrors: any[]) => { const userConfigModelParser = new ConfigurationModelParser(this.settingsPath); userConfigModelParser.parse(content); parseErrors = [...userConfigModelParser.errors]; return userConfigModelParser; }, initCallback: () => c(undefined) }); this._register(this.userConfigModelWatcher); // Listeners this._register(this.userConfigModelWatcher.onDidUpdateConfiguration(() => this._onDidChangeConfiguration.fire(this.userConfigModelWatcher.getConfig().configurationModel))); }); } return this.initializePromise.then(() => this.userConfigModelWatcher.getConfig().configurationModel); } initializeSync(): ConfigurationModel { this.initialize(); return this.userConfigModelWatcher.getConfig().configurationModel; } reload(): Promise<ConfigurationModel> { return this.initialize().then(() => new Promise<ConfigurationModel>(c => this.userConfigModelWatcher.reload(userConfigModelParser => c(userConfigModelParser.configurationModel)))); } }
src/vs/platform/configuration/node/configuration.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017522601410746574, 0.00017297234444413334, 0.00017102730635087937, 0.0001730553194647655, 0.0000015343960058089579 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tprivate static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] {\n", "\t\t// first sort by start (and end) and then loop over all elements\n", "\t\t// and build a tree based on containment.\n", "\t\tinfos = infos.slice(0).sort((a, b) => {\n", "\t\t\tlet res = a.location.range.start.compareTo(b.location.range.start);\n", "\t\t\tif (res === 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _asDocumentSymbolTree(infos: SymbolInformation[]): modes.DocumentSymbol[] {\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { clipboard } from 'electron'; import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands'; import { ContextKeyExpr, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { KeybindingsRegistry, KeybindingWeight, IKeybindings } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { localize } from 'vs/nls'; import { Marker, RelatedInformation } from 'vs/workbench/parts/markers/electron-browser/markersModel'; import { MarkersPanel } from 'vs/workbench/parts/markers/electron-browser/markersPanel'; import { MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { PanelRegistry, Extensions as PanelExtensions, PanelDescriptor } from 'vs/workbench/browser/panel'; import { Registry } from 'vs/platform/registry/common/platform'; import { ToggleMarkersPanelAction, ShowProblemsPanelAction } from 'vs/workbench/parts/markers/electron-browser/markersPanelActions'; import Constants from 'vs/workbench/parts/markers/electron-browser/constants'; import Messages from 'vs/workbench/parts/markers/electron-browser/messages'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IMarkersWorkbenchService, MarkersWorkbenchService, ActivityUpdater } from 'vs/workbench/parts/markers/electron-browser/markers'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import './markersFileDecorations'; registerSingleton(IMarkersWorkbenchService, MarkersWorkbenchService, false); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.MARKER_OPEN_SIDE_ACTION_ID, weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(Constants.MarkerFocusContextKey), primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, handler: (accessor, args: any) => { const markersPanel = (<MarkersPanel>accessor.get(IPanelService).getActivePanel()); markersPanel.openFileAtElement(markersPanel.getFocusElement(), false, true, true); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: Constants.MARKER_SHOW_PANEL_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor, args: any) => { accessor.get(IPanelService).openPanel(Constants.MARKERS_PANEL_ID); } }); // configuration Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({ 'id': 'problems', 'order': 101, 'title': Messages.PROBLEMS_PANEL_CONFIGURATION_TITLE, 'type': 'object', 'properties': { 'problems.autoReveal': { 'description': Messages.PROBLEMS_PANEL_CONFIGURATION_AUTO_REVEAL, 'type': 'boolean', 'default': true } } }); // markers panel Registry.as<PanelRegistry>(PanelExtensions.Panels).registerPanel(new PanelDescriptor( MarkersPanel, Constants.MARKERS_PANEL_ID, Messages.MARKERS_PANEL_TITLE_PROBLEMS, 'markersPanel', 10, ToggleMarkersPanelAction.ID )); // workbench const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(ActivityUpdater, LifecyclePhase.Restored); // actions const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); registry.registerWorkbenchAction(new SyncActionDescriptor(ToggleMarkersPanelAction, ToggleMarkersPanelAction.ID, ToggleMarkersPanelAction.LABEL, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_M }), 'View: Toggle Problems (Errors, Warnings, Infos)', Messages.MARKERS_PANEL_VIEW_CATEGORY); registry.registerWorkbenchAction(new SyncActionDescriptor(ShowProblemsPanelAction, ShowProblemsPanelAction.ID, ShowProblemsPanelAction.LABEL), 'View: Focus Problems (Errors, Warnings, Infos)', Messages.MARKERS_PANEL_VIEW_CATEGORY); registerAction({ id: Constants.MARKER_COPY_ACTION_ID, title: localize('copyMarker', "Copy"), handler(accessor) { copyMarker(accessor.get(IPanelService)); }, menu: { menuId: MenuId.ProblemsPanelContext, when: Constants.MarkerFocusContextKey, group: 'navigation' }, keybinding: { keys: { primary: KeyMod.CtrlCmd | KeyCode.KEY_C }, when: Constants.MarkerFocusContextKey } }); registerAction({ id: Constants.MARKER_COPY_MESSAGE_ACTION_ID, title: localize('copyMessage', "Copy Message"), handler(accessor) { copyMessage(accessor.get(IPanelService)); }, menu: { menuId: MenuId.ProblemsPanelContext, when: Constants.MarkerFocusContextKey, group: 'navigation' } }); registerAction({ id: Constants.RELATED_INFORMATION_COPY_MESSAGE_ACTION_ID, title: localize('copyMessage', "Copy Message"), handler(accessor) { copyRelatedInformationMessage(accessor.get(IPanelService)); }, menu: { menuId: MenuId.ProblemsPanelContext, when: Constants.RelatedInformationFocusContextKey, group: 'navigation' } }); registerAction({ id: Constants.FOCUS_PROBLEMS_FROM_FILTER, handler(accessor) { focusProblemsView(accessor.get(IPanelService)); }, keybinding: { when: Constants.MarkerPanelFilterFocusContextKey, keys: { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, } }); registerAction({ id: Constants.MARKERS_PANEL_FOCUS_FILTER, handler(accessor) { focusProblemsFilter(accessor.get(IPanelService)); }, keybinding: { when: Constants.MarkerPanelFocusContextKey, keys: { primary: KeyMod.CtrlCmd | KeyCode.KEY_F }, } }); registerAction({ id: Constants.MARKERS_PANEL_SHOW_MULTILINE_MESSAGE, handler(accessor) { const panelService = accessor.get(IPanelService); const panel = panelService.getActivePanel(); if (panel instanceof MarkersPanel) { panel.markersViewState.multiline = true; } }, title: localize('show multiline', "Show message in multiple lines"), category: localize('problems', "Problems"), menu: { menuId: MenuId.CommandPalette, when: new RawContextKey<string>('activePanel', Constants.MARKERS_PANEL_ID) } }); registerAction({ id: Constants.MARKERS_PANEL_SHOW_SINGLELINE_MESSAGE, handler(accessor) { const panelService = accessor.get(IPanelService); const panel = panelService.getActivePanel(); if (panel instanceof MarkersPanel) { panel.markersViewState.multiline = false; } }, title: localize('show singleline', "Show message in single line"), category: localize('problems', "Problems"), menu: { menuId: MenuId.CommandPalette, when: new RawContextKey<string>('activePanel', Constants.MARKERS_PANEL_ID) } }); function copyMarker(panelService: IPanelService) { const activePanel = panelService.getActivePanel(); if (activePanel instanceof MarkersPanel) { const element = (<MarkersPanel>activePanel).getFocusElement(); if (element instanceof Marker) { clipboard.writeText(`${element}`); } } } function copyMessage(panelService: IPanelService) { const activePanel = panelService.getActivePanel(); if (activePanel instanceof MarkersPanel) { const element = (<MarkersPanel>activePanel).getFocusElement(); if (element instanceof Marker) { clipboard.writeText(element.marker.message); } } } function copyRelatedInformationMessage(panelService: IPanelService) { const activePanel = panelService.getActivePanel(); if (activePanel instanceof MarkersPanel) { const element = (<MarkersPanel>activePanel).getFocusElement(); if (element instanceof RelatedInformation) { clipboard.writeText(element.raw.message); } } } function focusProblemsView(panelService: IPanelService) { const activePanel = panelService.getActivePanel(); if (activePanel instanceof MarkersPanel) { activePanel.focus(); } } function focusProblemsFilter(panelService: IPanelService) { const activePanel = panelService.getActivePanel(); if (activePanel instanceof MarkersPanel) { activePanel.focusFilter(); } } interface IActionDescriptor { id: string; handler: ICommandHandler; // ICommandUI title?: string; category?: string; f1?: boolean; // menu?: { menuId: MenuId, when?: ContextKeyExpr; group?: string; }; // keybinding?: { when?: ContextKeyExpr; weight?: number; keys: IKeybindings; }; } function registerAction(desc: IActionDescriptor) { const { id, handler, title, category, menu, keybinding } = desc; // 1) register as command CommandsRegistry.registerCommand(id, handler); // 2) menus let command = { id, title, category }; if (menu) { let { menuId, when, group } = menu; MenuRegistry.appendMenuItem(menuId, { command, when, group }); } // 3) keybindings if (keybinding) { let { when, weight, keys } = keybinding; KeybindingsRegistry.registerKeybindingRule({ id, when, weight, primary: keys.primary, secondary: keys.secondary, linux: keys.linux, mac: keys.mac, win: keys.win }); } } MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '4_panels', command: { id: ToggleMarkersPanelAction.ID, title: localize({ key: 'miMarker', comment: ['&& denotes a mnemonic'] }, "&&Problems") }, order: 4 });
src/vs/workbench/parts/markers/electron-browser/markers.contribution.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017704570200294256, 0.0001729756040731445, 0.00016512746515218168, 0.00017397159535903484, 0.000002622801048346446 ]
{ "id": 4, "code_window": [ "\t\tlet res: modes.DocumentSymbol[] = [];\n", "\t\tlet parentStack: modes.DocumentSymbol[] = [];\n", "\t\tfor (const info of infos) {\n", "\t\t\tlet element = <modes.DocumentSymbol>{\n", "\t\t\t\tname: info.name,\n", "\t\t\t\tkind: typeConvert.SymbolKind.from(info.kind),\n", "\t\t\t\tcontainerName: info.containerName,\n", "\t\t\t\trange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tselectionRange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tchildren: []\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9983772039413452, 0.02244611270725727, 0.00015891765360720456, 0.0001706096954876557, 0.1460464894771576 ]
{ "id": 4, "code_window": [ "\t\tlet res: modes.DocumentSymbol[] = [];\n", "\t\tlet parentStack: modes.DocumentSymbol[] = [];\n", "\t\tfor (const info of infos) {\n", "\t\t\tlet element = <modes.DocumentSymbol>{\n", "\t\t\t\tname: info.name,\n", "\t\t\t\tkind: typeConvert.SymbolKind.from(info.kind),\n", "\t\t\t\tcontainerName: info.containerName,\n", "\t\t\t\trange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tselectionRange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tchildren: []\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 69 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M2.22785 7.35986C2.69078 7.35986 3.01627 7.25136 3.20434 7.03436C3.33454 6.87523 3.39964 6.64376 3.39964 6.33996C3.39964 6.20976 3.38517 6.01808 3.35624 5.76492C3.32731 5.51176 3.31284 5.31646 3.31284 5.17902C3.31284 5.04159 3.30561 4.83544 3.29114 4.56058C3.26221 4.31465 3.24774 4.14105 3.24774 4.03978C3.24774 3.34539 3.45027 2.83183 3.85533 2.49909C4.2604 2.16636 4.83183 2 5.56962 2H6.11212V3.28029H5.83002C5.51175 3.28029 5.28391 3.37071 5.14647 3.55154C5.00904 3.73237 4.94033 4.00362 4.94033 4.36528C4.94033 4.45208 4.95479 4.58228 4.98372 4.75588C5.01266 4.97288 5.02712 5.13924 5.02712 5.25497C5.02712 5.34177 5.03436 5.4792 5.04882 5.66727C5.07776 5.92767 5.09222 6.1302 5.09222 6.27486C5.09222 6.82459 4.97649 7.23689 4.74503 7.51175C4.5425 7.75768 4.22423 7.93128 3.79024 8.03255C4.22423 8.14828 4.5425 8.32188 4.74503 8.55334C4.97649 8.84268 5.09222 9.25497 5.09222 9.79024C5.09222 9.94937 5.07776 10.1591 5.04882 10.4195C5.01989 10.6076 5.00904 10.745 5.01627 10.8318C5.02351 10.9186 5.01266 11.0705 4.98372 11.2875C4.95479 11.4467 4.94033 11.5624 4.94033 11.6347C4.94033 11.9964 5.00904 12.2676 5.14647 12.4485C5.28391 12.6293 5.51175 12.7197 5.83002 12.7197H6.11212V14H5.56962C4.0651 14 3.31284 13.3201 3.31284 11.9602C3.31284 11.4684 3.33816 11.0886 3.38879 10.821C3.43942 10.5533 3.46474 10.1664 3.46474 9.66004C3.46474 8.98011 3.08137 8.64014 2.31465 8.64014L2.22785 7.35986ZM13.7722 8.50995C13.0054 8.50995 12.6221 8.84991 12.6221 9.52984C12.6221 9.66004 12.6329 9.85172 12.6546 10.1049C12.6763 10.358 12.6872 10.5497 12.6872 10.6799C12.7306 10.9548 12.7523 11.3382 12.7523 11.83C12.7523 13.1899 11.9855 13.8698 10.4521 13.8698H9.90958V12.7197H10.17C10.4882 12.7197 10.7161 12.6293 10.8535 12.4485C10.991 12.2676 11.0597 11.9964 11.0597 11.6347C11.0597 11.2731 11.038 10.9982 10.9946 10.8101C10.9946 10.6944 10.9801 10.5244 10.9512 10.3002C10.9222 10.0759 10.9078 9.90597 10.9078 9.79024C10.9078 9.25497 11.0235 8.84268 11.255 8.55334C11.4575 8.32188 11.7758 8.14828 12.2098 8.03255C11.7758 7.93128 11.4575 7.75768 11.255 7.51175C11.0235 7.23689 10.9078 6.82459 10.9078 6.27486C10.9078 6.1302 10.9222 5.92767 10.9512 5.66727C10.9801 5.4792 10.9946 5.34177 10.9946 5.25497C11.038 5.02351 11.0597 4.73418 11.0597 4.38698C11.0597 4.03978 10.9873 3.77939 10.8427 3.60579C10.698 3.43219 10.4738 3.32369 10.17 3.28029H9.90958V2H10.4521C11.1754 2 11.7396 2.16636 12.1447 2.49909C12.5497 2.83183 12.7523 3.34539 12.7523 4.03978C12.7523 4.16998 12.7414 4.36166 12.7197 4.61483C12.698 4.86799 12.6872 5.05967 12.6872 5.18987C12.6438 5.46474 12.6148 5.8481 12.6004 6.33996C12.6148 6.64376 12.6799 6.87523 12.7957 7.03436C12.9837 7.25136 13.3092 7.35986 13.7722 7.35986V8.50995Z" fill="#C5C5C5"/> </svg>
src/vs/workbench/parts/preferences/electron-browser/media/edit-json-inverse.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0003644368262030184, 0.0003644368262030184, 0.0003644368262030184, 0.0003644368262030184, 0 ]
{ "id": 4, "code_window": [ "\t\tlet res: modes.DocumentSymbol[] = [];\n", "\t\tlet parentStack: modes.DocumentSymbol[] = [];\n", "\t\tfor (const info of infos) {\n", "\t\t\tlet element = <modes.DocumentSymbol>{\n", "\t\t\t\tname: info.name,\n", "\t\t\t\tkind: typeConvert.SymbolKind.from(info.kind),\n", "\t\t\t\tcontainerName: info.containerName,\n", "\t\t\t\trange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tselectionRange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tchildren: []\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Registry } from 'vs/platform/registry/common/platform'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { WorkspaceStats } from 'vs/workbench/parts/stats/node/workspaceStats'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; // Register Workspace Stats Contribution Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(WorkspaceStats, LifecyclePhase.Eventually);
src/vs/workbench/parts/stats/node/stats.contribution.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017398818454239517, 0.0001727555791148916, 0.000171522973687388, 0.0001727555791148916, 0.0000012326054275035858 ]
{ "id": 4, "code_window": [ "\t\tlet res: modes.DocumentSymbol[] = [];\n", "\t\tlet parentStack: modes.DocumentSymbol[] = [];\n", "\t\tfor (const info of infos) {\n", "\t\t\tlet element = <modes.DocumentSymbol>{\n", "\t\t\t\tname: info.name,\n", "\t\t\t\tkind: typeConvert.SymbolKind.from(info.kind),\n", "\t\t\t\tcontainerName: info.containerName,\n", "\t\t\t\trange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tselectionRange: typeConvert.Range.from(info.location.range),\n", "\t\t\t\tchildren: []\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as types from 'vs/base/common/types'; import { CursorContext, CursorState, ICursorSimpleModel, PartialCursorState, SingleCursorState } from 'vs/editor/common/controller/cursorCommon'; import { MoveOperations } from 'vs/editor/common/controller/cursorMoveOperations'; import { WordOperations } from 'vs/editor/common/controller/cursorWordOperations'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; export class CursorMoveCommands { public static addCursorDown(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): PartialCursorState[] { let result: PartialCursorState[] = [], resultLen = 0; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = CursorState.fromModelState(MoveOperations.translateDown(context.config, context.model, cursor.modelState)); } else { result[resultLen++] = CursorState.fromViewState(MoveOperations.translateDown(context.config, context.viewModel, cursor.viewState)); } } return result; } public static addCursorUp(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): PartialCursorState[] { let result: PartialCursorState[] = [], resultLen = 0; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = CursorState.fromModelState(MoveOperations.translateUp(context.config, context.model, cursor.modelState)); } else { result[resultLen++] = CursorState.fromViewState(MoveOperations.translateUp(context.config, context.viewModel, cursor.viewState)); } } return result; } public static moveToBeginningOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = this._moveToLineStart(context, cursor, inSelectionMode); } return result; } private static _moveToLineStart(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { const currentViewStateColumn = cursor.viewState.position.column; const currentModelStateColumn = cursor.modelState.position.column; const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn; const currentViewStatelineNumber = cursor.viewState.position.lineNumber; const firstNonBlankColumn = context.viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber); const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn; if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) { return this._moveToLineStartByView(context, cursor, inSelectionMode); } else { return this._moveToLineStartByModel(context, cursor, inSelectionMode); } } private static _moveToLineStartByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { return CursorState.fromViewState( MoveOperations.moveToBeginningOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode) ); } private static _moveToLineStartByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { return CursorState.fromModelState( MoveOperations.moveToBeginningOfLine(context.config, context.model, cursor.modelState, inSelectionMode) ); } public static moveToEndOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = this._moveToLineEnd(context, cursor, inSelectionMode); } return result; } private static _moveToLineEnd(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { const viewStatePosition = cursor.viewState.position; const viewModelMaxColumn = context.viewModel.getLineMaxColumn(viewStatePosition.lineNumber); const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn; const modelStatePosition = cursor.modelState.position; const modelMaxColumn = context.model.getLineMaxColumn(modelStatePosition.lineNumber); const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column; if (isEndOfViewLine || isEndLineOfWrappedLine) { return this._moveToLineEndByModel(context, cursor, inSelectionMode); } else { return this._moveToLineEndByView(context, cursor, inSelectionMode); } } private static _moveToLineEndByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { return CursorState.fromViewState( MoveOperations.moveToEndOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode) ); } private static _moveToLineEndByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState { return CursorState.fromModelState( MoveOperations.moveToEndOfLine(context.config, context.model, cursor.modelState, inSelectionMode) ); } public static expandLineSelection(context: CursorContext, cursors: CursorState[]): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewSelection = cursor.viewState.selection; const startLineNumber = viewSelection.startLineNumber; const lineCount = context.viewModel.getLineCount(); let endLineNumber = viewSelection.endLineNumber; let endColumn: number; if (endLineNumber === lineCount) { endColumn = context.viewModel.getLineMaxColumn(lineCount); } else { endLineNumber++; endColumn = 1; } result[i] = CursorState.fromViewState(new SingleCursorState( new Range(startLineNumber, 1, startLineNumber, 1), 0, new Position(endLineNumber, endColumn), 0 )); } return result; } public static moveToBeginningOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromModelState(MoveOperations.moveToBeginningOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode)); } return result; } public static moveToEndOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromModelState(MoveOperations.moveToEndOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode)); } return result; } public static selectAll(context: CursorContext, cursor: CursorState): PartialCursorState { const lineCount = context.model.getLineCount(); const maxColumn = context.model.getLineMaxColumn(lineCount); return CursorState.fromModelState(new SingleCursorState( new Range(1, 1, 1, 1), 0, new Position(lineCount, maxColumn), 0 )); } public static line(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): PartialCursorState { const position = context.model.validatePosition(_position); const viewPosition = ( _viewPosition ? context.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position) : context.convertModelPositionToViewPosition(position) ); if (!inSelectionMode || !cursor.modelState.hasSelection()) { // Entering line selection for the first time const lineCount = context.model.getLineCount(); let selectToLineNumber = position.lineNumber + 1; let selectToColumn = 1; if (selectToLineNumber > lineCount) { selectToLineNumber = lineCount; selectToColumn = context.model.getLineMaxColumn(selectToLineNumber); } return CursorState.fromModelState(new SingleCursorState( new Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new Position(selectToLineNumber, selectToColumn), 0 )); } // Continuing line selection const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber; if (position.lineNumber < enteringLineNumber) { return CursorState.fromViewState(cursor.viewState.move( cursor.modelState.hasSelection(), viewPosition.lineNumber, 1, 0 )); } else if (position.lineNumber > enteringLineNumber) { const lineCount = context.viewModel.getLineCount(); let selectToViewLineNumber = viewPosition.lineNumber + 1; let selectToViewColumn = 1; if (selectToViewLineNumber > lineCount) { selectToViewLineNumber = lineCount; selectToViewColumn = context.viewModel.getLineMaxColumn(selectToViewLineNumber); } return CursorState.fromViewState(cursor.viewState.move( cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0 )); } else { const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition(); return CursorState.fromModelState(cursor.modelState.move( cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0 )); } } public static word(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition): PartialCursorState { const position = context.model.validatePosition(_position); return CursorState.fromModelState(WordOperations.word(context.config, context.model, cursor.modelState, inSelectionMode, position)); } public static cancelSelection(context: CursorContext, cursor: CursorState): PartialCursorState { if (!cursor.modelState.hasSelection()) { return new CursorState(cursor.modelState, cursor.viewState); } const lineNumber = cursor.viewState.position.lineNumber; const column = cursor.viewState.position.column; return CursorState.fromViewState(new SingleCursorState( new Range(lineNumber, column, lineNumber, column), 0, new Position(lineNumber, column), 0 )); } public static moveTo(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): PartialCursorState { const position = context.model.validatePosition(_position); const viewPosition = ( _viewPosition ? context.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position) : context.convertModelPositionToViewPosition(position) ); return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0)); } public static move(context: CursorContext, cursors: CursorState[], args: CursorMove.ParsedArguments): PartialCursorState[] | null { const inSelectionMode = args.select; const value = args.value; switch (args.direction) { case CursorMove.Direction.Left: { if (args.unit === CursorMove.Unit.HalfLine) { // Move left by half the current line length return this._moveHalfLineLeft(context, cursors, inSelectionMode); } else { // Move left by `moveParams.value` columns return this._moveLeft(context, cursors, inSelectionMode, value); } } case CursorMove.Direction.Right: { if (args.unit === CursorMove.Unit.HalfLine) { // Move right by half the current line length return this._moveHalfLineRight(context, cursors, inSelectionMode); } else { // Move right by `moveParams.value` columns return this._moveRight(context, cursors, inSelectionMode, value); } } case CursorMove.Direction.Up: { if (args.unit === CursorMove.Unit.WrappedLine) { // Move up by view lines return this._moveUpByViewLines(context, cursors, inSelectionMode, value); } else { // Move up by model lines return this._moveUpByModelLines(context, cursors, inSelectionMode, value); } } case CursorMove.Direction.Down: { if (args.unit === CursorMove.Unit.WrappedLine) { // Move down by view lines return this._moveDownByViewLines(context, cursors, inSelectionMode, value); } else { // Move down by model lines return this._moveDownByModelLines(context, cursors, inSelectionMode, value); } } case CursorMove.Direction.WrappedLineStart: { // Move to the beginning of the current view line return this._moveToViewMinColumn(context, cursors, inSelectionMode); } case CursorMove.Direction.WrappedLineFirstNonWhitespaceCharacter: { // Move to the first non-whitespace column of the current view line return this._moveToViewFirstNonWhitespaceColumn(context, cursors, inSelectionMode); } case CursorMove.Direction.WrappedLineColumnCenter: { // Move to the "center" of the current view line return this._moveToViewCenterColumn(context, cursors, inSelectionMode); } case CursorMove.Direction.WrappedLineEnd: { // Move to the end of the current view line return this._moveToViewMaxColumn(context, cursors, inSelectionMode); } case CursorMove.Direction.WrappedLineLastNonWhitespaceCharacter: { // Move to the last non-whitespace column of the current view line return this._moveToViewLastNonWhitespaceColumn(context, cursors, inSelectionMode); } case CursorMove.Direction.ViewPortTop: { // Move to the nth line start in the viewport (from the top) const cursor = cursors[0]; const visibleModelRange = context.getCompletelyVisibleModelRange(); const modelLineNumber = this._firstLineNumberInRange(context.model, visibleModelRange, value); const modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case CursorMove.Direction.ViewPortBottom: { // Move to the nth line start in the viewport (from the bottom) const cursor = cursors[0]; const visibleModelRange = context.getCompletelyVisibleModelRange(); const modelLineNumber = this._lastLineNumberInRange(context.model, visibleModelRange, value); const modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case CursorMove.Direction.ViewPortCenter: { // Move to the line start in the viewport center const cursor = cursors[0]; const visibleModelRange = context.getCompletelyVisibleModelRange(); const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2); const modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)]; } case CursorMove.Direction.ViewPortIfOutside: { // Move to a position inside the viewport const visibleViewRange = context.getCompletelyVisibleViewRange(); let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = this.findPositionInViewportIfOutside(context, cursor, visibleViewRange, inSelectionMode); } return result; } } return null; } public static findPositionInViewportIfOutside(context: CursorContext, cursor: CursorState, visibleViewRange: Range, inSelectionMode: boolean): PartialCursorState { let viewLineNumber = cursor.viewState.position.lineNumber; if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) { // Nothing to do, cursor is in viewport return new CursorState(cursor.modelState, cursor.viewState); } else { if (viewLineNumber > visibleViewRange.endLineNumber - 1) { viewLineNumber = visibleViewRange.endLineNumber - 1; } if (viewLineNumber < visibleViewRange.startLineNumber) { viewLineNumber = visibleViewRange.startLineNumber; } const viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); return this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } } /** * Find the nth line start included in the range (from the start). */ private static _firstLineNumberInRange(model: ICursorSimpleModel, range: Range, count: number): number { let startLineNumber = range.startLineNumber; if (range.startColumn !== model.getLineMinColumn(startLineNumber)) { // Move on to the second line if the first line start is not included in the range startLineNumber++; } return Math.min(range.endLineNumber, startLineNumber + count - 1); } /** * Find the nth line start included in the range (from the end). */ private static _lastLineNumberInRange(model: ICursorSimpleModel, range: Range, count: number): number { let startLineNumber = range.startLineNumber; if (range.startColumn !== model.getLineMinColumn(startLineNumber)) { // Move on to the second line if the first line start is not included in the range startLineNumber++; } return Math.max(startLineNumber, range.endLineNumber - count + 1); } private static _moveLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; let newViewState = MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns); if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) { // moved over to the previous view line const newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position); if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) { // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position newViewState = MoveOperations.moveLeft(context.config, context.viewModel, newViewState, inSelectionMode, 1); } } result[i] = CursorState.fromViewState(newViewState); } return result; } private static _moveHalfLineLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2); result[i] = CursorState.fromViewState(MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; } private static _moveRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; let newViewState = MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns); if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) { // moved over to the next view line const newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position); if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) { // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position newViewState = MoveOperations.moveRight(context.config, context.viewModel, newViewState, inSelectionMode, 1); } } result[i] = CursorState.fromViewState(newViewState); } return result; } private static _moveHalfLineRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2); result[i] = CursorState.fromViewState(MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; } private static _moveDownByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromViewState(MoveOperations.moveDown(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; } private static _moveDownByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromModelState(MoveOperations.moveDown(context.config, context.model, cursor.modelState, inSelectionMode, linesCount)); } return result; } private static _moveUpByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromViewState(MoveOperations.moveUp(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; } private static _moveUpByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; result[i] = CursorState.fromModelState(MoveOperations.moveUp(context.config, context.model, cursor.modelState, inSelectionMode, linesCount)); } return result; } private static _moveToViewPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toViewLineNumber: number, toViewColumn: number): PartialCursorState { return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0)); } private static _moveToModelPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toModelLineNumber: number, toModelColumn: number): PartialCursorState { return CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0)); } private static _moveToViewMinColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = context.viewModel.getLineMinColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } private static _moveToViewFirstNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } private static _moveToViewCenterColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = Math.round((context.viewModel.getLineMaxColumn(viewLineNumber) + context.viewModel.getLineMinColumn(viewLineNumber)) / 2); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } private static _moveToViewMaxColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = context.viewModel.getLineMaxColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } private static _moveToViewLastNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] { let result: PartialCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { const cursor = cursors[i]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = context.viewModel.getLineLastNonWhitespaceColumn(viewLineNumber); result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } } export namespace CursorMove { const isCursorMoveArgs = function (arg: any): boolean { if (!types.isObject(arg)) { return false; } let cursorMoveArg: RawArguments = arg; if (!types.isString(cursorMoveArg.to)) { return false; } if (!types.isUndefined(cursorMoveArg.select) && !types.isBoolean(cursorMoveArg.select)) { return false; } if (!types.isUndefined(cursorMoveArg.by) && !types.isString(cursorMoveArg.by)) { return false; } if (!types.isUndefined(cursorMoveArg.value) && !types.isNumber(cursorMoveArg.value)) { return false; } return true; }; export const description = <ICommandHandlerDescription>{ description: 'Move cursor to a logical position in the view', args: [ { name: 'Cursor move argument object', description: `Property-value pairs that can be passed through this argument: * 'to': A mandatory logical position value providing where to move the cursor. \`\`\` 'left', 'right', 'up', 'down' 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter' 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter' 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside' \`\`\` * 'by': Unit to move. Default is computed based on 'to' value. \`\`\` 'line', 'wrappedLine', 'character', 'halfLine' \`\`\` * 'value': Number of units to move. Default is '1'. * 'select': If 'true' makes the selection. Default is 'false'. `, constraint: isCursorMoveArgs } ] }; /** * Positions in the view for cursor move command. */ export const RawDirection = { Left: 'left', Right: 'right', Up: 'up', Down: 'down', WrappedLineStart: 'wrappedLineStart', WrappedLineFirstNonWhitespaceCharacter: 'wrappedLineFirstNonWhitespaceCharacter', WrappedLineColumnCenter: 'wrappedLineColumnCenter', WrappedLineEnd: 'wrappedLineEnd', WrappedLineLastNonWhitespaceCharacter: 'wrappedLineLastNonWhitespaceCharacter', ViewPortTop: 'viewPortTop', ViewPortCenter: 'viewPortCenter', ViewPortBottom: 'viewPortBottom', ViewPortIfOutside: 'viewPortIfOutside' }; /** * Units for Cursor move 'by' argument */ export const RawUnit = { Line: 'line', WrappedLine: 'wrappedLine', Character: 'character', HalfLine: 'halfLine' }; /** * Arguments for Cursor move command */ export interface RawArguments { to: string; select?: boolean; by?: string; value?: number; } export function parse(args: RawArguments): ParsedArguments | null { if (!args.to) { // illegal arguments return null; } let direction: Direction; switch (args.to) { case RawDirection.Left: direction = Direction.Left; break; case RawDirection.Right: direction = Direction.Right; break; case RawDirection.Up: direction = Direction.Up; break; case RawDirection.Down: direction = Direction.Down; break; case RawDirection.WrappedLineStart: direction = Direction.WrappedLineStart; break; case RawDirection.WrappedLineFirstNonWhitespaceCharacter: direction = Direction.WrappedLineFirstNonWhitespaceCharacter; break; case RawDirection.WrappedLineColumnCenter: direction = Direction.WrappedLineColumnCenter; break; case RawDirection.WrappedLineEnd: direction = Direction.WrappedLineEnd; break; case RawDirection.WrappedLineLastNonWhitespaceCharacter: direction = Direction.WrappedLineLastNonWhitespaceCharacter; break; case RawDirection.ViewPortTop: direction = Direction.ViewPortTop; break; case RawDirection.ViewPortBottom: direction = Direction.ViewPortBottom; break; case RawDirection.ViewPortCenter: direction = Direction.ViewPortCenter; break; case RawDirection.ViewPortIfOutside: direction = Direction.ViewPortIfOutside; break; default: // illegal arguments return null; } let unit = Unit.None; switch (args.by) { case RawUnit.Line: unit = Unit.Line; break; case RawUnit.WrappedLine: unit = Unit.WrappedLine; break; case RawUnit.Character: unit = Unit.Character; break; case RawUnit.HalfLine: unit = Unit.HalfLine; break; } return { direction: direction, unit: unit, select: (!!args.select), value: (args.value || 1) }; } export interface ParsedArguments { direction: Direction; unit: Unit; select: boolean; value: number; } export const enum Direction { Left, Right, Up, Down, WrappedLineStart, WrappedLineFirstNonWhitespaceCharacter, WrappedLineColumnCenter, WrappedLineEnd, WrappedLineLastNonWhitespaceCharacter, ViewPortTop, ViewPortCenter, ViewPortBottom, ViewPortIfOutside, } export const enum Unit { None, Line, WrappedLine, Character, HalfLine, } }
src/vs/editor/common/controller/cursorMoveCommands.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00024338062212336808, 0.00017228952492587268, 0.0001649417681619525, 0.00017179713177029043, 0.000008427606189798098 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "class CodeLensAdapter {\n", "\n", "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' };\n", "\n", "\tconstructor(\n", "\t\tprivate readonly _documents: ExtHostDocuments,\n", "\t\tprivate readonly _commands: CommandsConverter,\n", "\t\tprivate readonly _heapService: ExtHostHeapService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '!!MISSING: command!!' };\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9992801547050476, 0.044217415153980255, 0.00016691407654434443, 0.00020954495994374156, 0.19771219789981842 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "class CodeLensAdapter {\n", "\n", "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' };\n", "\n", "\tconstructor(\n", "\t\tprivate readonly _documents: ExtHostDocuments,\n", "\t\tprivate readonly _commands: CommandsConverter,\n", "\t\tprivate readonly _heapService: ExtHostHeapService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '!!MISSING: command!!' };\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import VsCodeTelemetryReporter from 'vscode-extension-telemetry'; import { memoize } from './memoize'; interface PackageInfo { readonly name: string; readonly version: string; readonly aiKey: string; } export default class TelemetryReporter { private _reporter: VsCodeTelemetryReporter | null = null; dispose() { if (this._reporter) { this._reporter.dispose(); this._reporter = null; } } constructor( private readonly clientVersionDelegate: () => string ) { } public logTelemetry(eventName: string, properties?: { [prop: string]: string }) { const reporter = this.reporter; if (reporter) { if (!properties) { properties = {}; } /* __GDPR__FRAGMENT__ "TypeScriptCommonProperties" : { "version" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ properties['version'] = this.clientVersionDelegate(); reporter.sendTelemetryEvent(eventName, properties); } } @memoize private get reporter(): VsCodeTelemetryReporter | null { if (this.packageInfo && this.packageInfo.aiKey) { this._reporter = new VsCodeTelemetryReporter( this.packageInfo.name, this.packageInfo.version, this.packageInfo.aiKey); return this._reporter; } return null; } @memoize private get packageInfo(): PackageInfo | null { const { packageJSON } = vscode.extensions.getExtension('vscode.typescript-language-features')!; if (packageJSON) { return { name: packageJSON.name, version: packageJSON.version, aiKey: packageJSON.aiKey }; } return null; } }
extensions/typescript-language-features/src/utils/telemetry.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0004460331401787698, 0.00021760414529126137, 0.00016308794147334993, 0.00017110179760493338, 0.00009382965072290972 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "class CodeLensAdapter {\n", "\n", "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' };\n", "\n", "\tconstructor(\n", "\t\tprivate readonly _documents: ExtHostDocuments,\n", "\t\tprivate readonly _commands: CommandsConverter,\n", "\t\tprivate readonly _heapService: ExtHostHeapService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '!!MISSING: command!!' };\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as es from 'event-stream'; import * as _ from 'underscore'; import * as util from 'gulp-util'; import * as fs from 'fs'; import * as path from 'path'; const allErrors: string[][] = []; let startTime: number | null = null; let count = 0; function onStart(): void { if (count++ > 0) { return; } startTime = new Date().getTime(); util.log(`Starting ${util.colors.green('compilation')}...`); } function onEnd(): void { if (--count > 0) { return; } log(); } const buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log'); try { fs.mkdirSync(path.dirname(buildLogPath)); } catch (err) { // ignore } function log(): void { const errors = _.flatten(allErrors); const seen = new Set<string>(); errors.map(err => { if (!seen.has(err)) { seen.add(err); util.log(`${util.colors.red('Error')}: ${err}`); } }); const regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/; const messages = errors .map(err => regex.exec(err)) .filter(match => !!match) .map(x => x as string[]) .map(([, path, line, column, message]) => ({ path, line: parseInt(line), column: parseInt(column), message })); try { fs.writeFileSync(buildLogPath, JSON.stringify(messages)); } catch (err) { //noop } util.log(`Finished ${util.colors.green('compilation')} with ${errors.length} errors after ${util.colors.magenta((new Date().getTime() - startTime!) + ' ms')}`); } export interface IReporter { (err: string): void; hasErrors(): boolean; end(emitError: boolean): NodeJS.ReadWriteStream; } export function createReporter(): IReporter { const errors: string[] = []; allErrors.push(errors); const result = (err: string) => errors.push(err); result.hasErrors = () => errors.length > 0; result.end = (emitError: boolean): NodeJS.ReadWriteStream => { errors.length = 0; onStart(); return es.through(undefined, function () { onEnd(); if (emitError && errors.length > 0) { if (!(errors as any).__logged__) { log(); } (errors as any).__logged__ = true; const err = new Error(`Found ${errors.length} errors`); (err as any).__reporter__ = true; this.emit('error', err); } else { this.emit('end'); } }); }; return result; }
build/lib/reporter.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017733561981003731, 0.00017050681344699115, 0.00016202805272769183, 0.0001709570351522416, 0.0000035099196793453302 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "class CodeLensAdapter {\n", "\n", "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' };\n", "\n", "\tconstructor(\n", "\t\tprivate readonly _documents: ExtHostDocuments,\n", "\t\tprivate readonly _commands: CommandsConverter,\n", "\t\tprivate readonly _heapService: ExtHostHeapService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static _badCmd: vscode.Command = { command: 'missing', title: '!!MISSING: command!!' };\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench .part.editor.has-watermark > .content.empty .editor-group-container > .editor-group-letterpress { background-position-y: calc(50% - 100px); } .monaco-workbench .part.editor.max-height-478px > .content.empty .editor-group-container > .editor-group-letterpress { background-position-y: 50%; } .monaco-workbench > .part.editor > .content > .watermark { display: none; /* only visible when no editors are opened */ } .monaco-workbench > .part.editor.has-watermark > .content.empty > .watermark { display: block; position: absolute; width: 100%; top: calc(50% + 55px); text-align: center; white-space: nowrap; overflow: hidden; } .monaco-workbench > .part.editor > .content.empty > .watermark > .watermark-box { display: inline-table; border-collapse: separate; border-spacing: 13px 17px; } .monaco-workbench > .part.editor.max-height-478px > .content.empty > .watermark { display: none; } .monaco-workbench > .part.editor > .content.empty > .watermark dl { display: table-row; opacity: .8; cursor: default; } .monaco-workbench > .part.editor > .content.empty > .watermark dt { text-align: right; letter-spacing: 0.04em } .monaco-workbench > .part.editor > .content.empty > .watermark dd { text-align: left; } .monaco-workbench > .part.editor > .content.empty > .watermark dd > .shortcuts { padding-left: 0.5em; padding-right: 0.5em; } .mac > .monaco-workbench > .part.editor > .content.empty > .watermark dd > .shortcuts { letter-spacing: 0.15em; font-family: "Lucida Grande", sans-serif; } .monaco-workbench > .part.editor > .content.empty > .watermark dd > .unbound { padding-left: 0.5em; padding-right: 0.5em; } .mac > .monaco-workbench > .part.editor > .content.empty > .watermark dd > .unbound { font-family: "Lucida Grande", sans-serif; } .monaco-workbench > .part.editor > .content.empty > .watermark dt, .monaco-workbench > .part.editor > .content.empty > .watermark dd { display: table-cell; } .monaco-workbench > .part.editor > .content.empty > .watermark dt, .monaco-workbench > .part.editor > .content.empty > .watermark dl { color: rgba(0,0,0,.68); } .vs-dark .monaco-workbench > .part.editor > .content.empty > .watermark dt, .vs-dark .monaco-workbench > .part.editor > .content.empty > .watermark dl { color: rgba(255,255,255,.6); } .hc-black .monaco-workbench > .part.editor > .content.empty > .watermark dt { color: #FFF; } .hc-black .monaco-workbench > .part.editor > .content.empty > .watermark dl { color: #FFF; opacity: 1; }
src/vs/workbench/parts/watermark/electron-browser/watermark.css
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017526763258501887, 0.000173101550899446, 0.00017063245468307287, 0.0001730309595586732, 0.000001328363055108639 ]
{ "id": 6, "code_window": [ "\t}\n", "}\n", "\n", "type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n", "\t| DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter\n", "\t| RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter\n", "\t| SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter\n", "\t| ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "type Adapter = DocumentSymbolAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 877 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.997349739074707, 0.03317771852016449, 0.00016217889788094908, 0.00017330999253317714, 0.15997189283370972 ]
{ "id": 6, "code_window": [ "\t}\n", "}\n", "\n", "type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n", "\t| DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter\n", "\t| RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter\n", "\t| SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter\n", "\t| ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "type Adapter = DocumentSymbolAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 877 }
/*--------------------------------------------------------------------------------------------- * 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 { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { Action } from 'vs/base/common/actions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { URI } from 'vs/base/common/uri'; import { WalkThroughInput, WalkThroughInputOptions } from 'vs/workbench/parts/welcome/walkThrough/node/walkThroughInput'; import { Schemas } from 'vs/base/common/network'; import { IEditorInputFactory, EditorInput } from 'vs/workbench/common/editor'; const typeId = 'workbench.editors.walkThroughInput'; const inputOptions: WalkThroughInputOptions = { typeId, name: localize('editorWalkThrough.title', "Interactive Playground"), resource: URI.parse(require.toUrl('./vs_code_editor_walkthrough.md')) .with({ scheme: Schemas.walkThrough }), telemetryFrom: 'walkThrough' }; export class EditorWalkThroughAction extends Action { public static readonly ID = 'workbench.action.showInteractivePlayground'; public static readonly LABEL = localize('editorWalkThrough', "Interactive Playground"); constructor( id: string, label: string, @IEditorService private readonly editorService: IEditorService, @IInstantiationService private readonly instantiationService: IInstantiationService ) { super(id, label); } public run(): Promise<void> { const input = this.instantiationService.createInstance(WalkThroughInput, inputOptions); return this.editorService.openEditor(input, { pinned: true }) .then(() => void (0)); } } export class EditorWalkThroughInputFactory implements IEditorInputFactory { static readonly ID = typeId; public serialize(editorInput: EditorInput): string { return '{}'; } public deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): WalkThroughInput { return instantiationService.createInstance(WalkThroughInput, inputOptions); } }
src/vs/workbench/parts/welcome/walkThrough/electron-browser/editor/editorWalkThrough.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00019221100956201553, 0.0001751649397192523, 0.0001689518103376031, 0.00017181401199195534, 0.0000078245875556604 ]
{ "id": 6, "code_window": [ "\t}\n", "}\n", "\n", "type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n", "\t| DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter\n", "\t| RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter\n", "\t| SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter\n", "\t| ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "type Adapter = DocumentSymbolAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 877 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/minimatch@^3.0.3": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/node@^8.10.25": version "8.10.25" resolved "https://registry.yarnpkg.com/@types/node/-/node-8.10.25.tgz#801fe4e39372cef18f268db880a5fbfcf71adc7e" integrity sha512-WXvAXaknB0c2cJ7N44e1kUrVu5K90mSfPPaT5XxfuSMxEWva86EYIwxUZM3jNZ2P1CIC9e2z4WJqpAF69PQxeA== agent-base@4, agent-base@^4.1.0: version "4.2.0" resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.2.0.tgz#9838b5c3392b962bad031e6a4c5e1024abec45ce" integrity sha512-c+R/U5X+2zz2+UCrCFv6odQzJdoqI+YecuhnAJLa1zYaMc13zPfwMwZrr91Pd1DYNo/yPRbiM4WVf9whgwFsIg== dependencies: es6-promisify "^5.0.0" 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= [email protected], debug@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g== dependencies: ms "2.0.0" es6-promise@^4.0.3: version "4.2.4" resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.4.tgz#dc4221c2b16518760bd8c39a52d8f356fc00ed29" integrity sha512-/NdNZVJg+uZgtm9eS3O6lrOLYmQag2DjdEXuPaHlZ6RuVqgqaVZfgYCepEIKsLqwdQArOPtC3XzRLqGGfT8KQQ== es6-promisify@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/es6-promisify/-/es6-promisify-5.0.0.tgz#5109d62f3e56ea967c4b63505aef08291c8a5203" integrity sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM= dependencies: es6-promise "^4.0.3" http-proxy-agent@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz#e4821beef5b2142a2026bd73926fe537631c5405" integrity sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg== dependencies: agent-base "4" debug "3.1.0" https-proxy-agent@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz#51552970fa04d723e04c56d04178c3f92592bbc0" integrity sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ== dependencies: agent-base "^4.1.0" debug "^3.1.0" jsonc-parser@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-2.0.2.tgz#42fcf56d70852a043fadafde51ddb4a85649978d" integrity sha512-TSU435K5tEKh3g7bam1AFf+uZrISheoDsLlpmAo6wWZYqjsnd09lHYK1Qo+moK4Ikifev1Gdpa69g4NELKnCrQ== 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" [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= request-light@^0.2.4: version "0.2.4" resolved "https://registry.yarnpkg.com/request-light/-/request-light-0.2.4.tgz#3cea29c126682e6bcadf7915353322eeba01a755" integrity sha512-pM9Fq5jRnSb+82V7M97rp8FE9/YNeP2L9eckB4Szd7lyeclSIx02aIpPO/6e4m6Dy31+FBN/zkFMTd2HkNO3ow== dependencies: http-proxy-agent "^2.1.0" https-proxy-agent "^2.2.1" vscode-nls "^4.0.0" vscode-nls@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002" integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
extensions/npm/yarn.lock
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017330865375697613, 0.00016923260409384966, 0.0001655127271078527, 0.00017002358799800277, 0.0000025893712063407293 ]
{ "id": 6, "code_window": [ "\t}\n", "}\n", "\n", "type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n", "\t| DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter\n", "\t| RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter\n", "\t| SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter\n", "\t| ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "type Adapter = DocumentSymbolAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 877 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const assert = require("assert"); const i18n = require("../i18n"); suite('XLF Parser Tests', () => { const sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source></trans-unit></body></file></xliff>'; const sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source><target>Кнопка #2 &amp;</target></trans-unit></body></file></xliff>'; const originalFilePath = 'vs/base/common/keybinding'; const keys = ['key1', 'key2']; const messages = ['Key #1', 'Key #2 &']; const translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' }; test('Keys & messages to XLF conversion', () => { const xlf = new i18n.XLF('vscode-workbench'); xlf.addFile(originalFilePath, keys, messages); const xlfString = xlf.toString(); assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf); }); test('XLF to keys & messages conversion', () => { i18n.XLF.parse(sampleTranslatedXlf).then(function (resolvedFiles) { assert.deepEqual(resolvedFiles[0].messages, translatedMessages); assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath); }); }); test('JSON file source path to Transifex resource match', () => { const editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench'; const platform = { name: 'vs/platform', project: editorProject }, editorContrib = { name: 'vs/editor/contrib', project: editorProject }, editor = { name: 'vs/editor', project: editorProject }, base = { name: 'vs/base', project: editorProject }, code = { name: 'vs/code', project: workbenchProject }, workbenchParts = { name: 'vs/workbench/parts/html', project: workbenchProject }, workbenchServices = { name: 'vs/workbench/services/files', project: workbenchProject }, workbench = { name: 'vs/workbench', project: workbenchProject }; assert.deepEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform); assert.deepEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib); assert.deepEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor); assert.deepEqual(i18n.getResource('vs/base/common/errorMessage'), base); assert.deepEqual(i18n.getResource('vs/code/electron-main/window'), code); assert.deepEqual(i18n.getResource('vs/workbench/parts/html/browser/webview'), workbenchParts); assert.deepEqual(i18n.getResource('vs/workbench/services/files/node/fileService'), workbenchServices); assert.deepEqual(i18n.getResource('vs/workbench/browser/parts/panel/panelActions'), workbench); }); });
build/lib/test/i18n.test.js
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0001755536359269172, 0.0001736497215460986, 0.00017298110469710082, 0.0001731535594444722, 9.705806860438315e-7 ]
{ "id": 7, "code_window": [ "\n", "\t// --- outline\n", "\n", "\tregisterDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {\n", "\t\tconst handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension);\n", "\t\tconst displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined;\n", "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst handle = this._addNewAdapter(new DocumentSymbolAdapter(this._documents, provider), extension);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1004 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9985659718513489, 0.10630329698324203, 0.00016315575339831412, 0.00019035559671465307, 0.27509889006614685 ]
{ "id": 7, "code_window": [ "\n", "\t// --- outline\n", "\n", "\tregisterDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {\n", "\t\tconst handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension);\n", "\t\tconst displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined;\n", "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst handle = this._addNewAdapter(new DocumentSymbolAdapter(this._documents, provider), extension);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1004 }
/*--------------------------------------------------------------------------------------------- * 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 * as dom from 'vs/base/browser/dom'; import { generateUuid } from 'vs/base/common/uuid'; import { appendStylizedStringToContainer, handleANSIOutput } from 'vs/workbench/parts/debug/browser/debugANSIHandling'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices'; import { LinkDetector } from 'vs/workbench/parts/debug/browser/linkDetector'; suite('Debug - ANSI Handling', () => { let linkDetector: LinkDetector; /** * Instantiate a {@link LinkDetector} for use by the functions being tested. */ setup(() => { const instantiationService: TestInstantiationService = <TestInstantiationService>workbenchInstantiationService(); linkDetector = instantiationService.createInstance(LinkDetector); }); test('appendStylizedStringToContainer', () => { const root: HTMLSpanElement = document.createElement('span'); let child: Node; assert.equal(0, root.children.length); appendStylizedStringToContainer(root, 'content1', ['class1', 'class2'], linkDetector); appendStylizedStringToContainer(root, 'content2', ['class2', 'class3'], linkDetector); assert.equal(2, root.children.length); child = root.firstChild!; if (child instanceof HTMLSpanElement) { assert.equal('content1', child.textContent); assert(dom.hasClass(child, 'class1')); assert(dom.hasClass(child, 'class2')); } else { assert.fail('Unexpected assertion error'); } child = root.lastChild!; if (child instanceof HTMLSpanElement) { assert.equal('content2', child.textContent); assert(dom.hasClass(child, 'class2')); assert(dom.hasClass(child, 'class3')); } else { assert.fail('Unexpected assertion error'); } }); /** * Apply an ANSI sequence to {@link #getSequenceOutput}. * * @param sequence The ANSI sequence to stylize. * @returns An {@link HTMLSpanElement} that contains the stylized text. */ function getSequenceOutput(sequence: string): HTMLSpanElement { const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector); assert.equal(1, root.children.length); const child: Node = root.lastChild!; if (child instanceof HTMLSpanElement) { return child; } else { assert.fail('Unexpected assertion error'); return null!; } } /** * Assert that a given ANSI sequence maintains added content following the ANSI code, and that * the provided {@param assertion} passes. * * @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes * only, and should not include actual text content as it is provided by this function. * @param assertion The function used to verify the output. */ function assertSingleSequenceElement(sequence: string, assertion: (child: HTMLSpanElement) => void): void { const child: HTMLSpanElement = getSequenceOutput(sequence + 'content'); assert.equal('content', child.textContent); assertion(child); } test('Expected single sequence operation', () => { // Bold code assertSingleSequenceElement('\x1b[1m', (child) => { assert(dom.hasClass(child, 'code-bold')); }); // Underline code assertSingleSequenceElement('\x1b[4m', (child) => { assert(dom.hasClass(child, 'code-underline')); }); for (let i = 30; i <= 37; i++) { const style: string = 'code-foreground-' + i; // Foreground colour codes assertSingleSequenceElement('\x1b[' + i + 'm', (child) => { assert(dom.hasClass(child, style)); }); // Cancellation code removes colour code assertSingleSequenceElement('\x1b[' + i + ';39m', (child) => { assert(dom.hasClass(child, style) === false); }); } for (let i = 40; i <= 47; i++) { const style: string = 'code-background-' + i; // Foreground colour codes assertSingleSequenceElement('\x1b[' + i + 'm', (child) => { assert(dom.hasClass(child, style)); }); // Cancellation code removes colour code assertSingleSequenceElement('\x1b[' + i + ';49m', (child) => { assert(dom.hasClass(child, style) === false); }); } // Codes do not interfere assertSingleSequenceElement('\x1b[1;4;30;31;32;33;34;35;36;37m', (child) => { assert.equal(10, child.classList.length); assert(dom.hasClass(child, 'code-bold')); assert(dom.hasClass(child, 'code-underline')); for (let i = 30; i <= 37; i++) { assert(dom.hasClass(child, 'code-foreground-' + i)); } }); // Duplicate codes do not change output assertSingleSequenceElement('\x1b[1;1;4;1;4;4;1;4m', (child) => { assert(dom.hasClass(child, 'code-bold')); assert(dom.hasClass(child, 'code-underline')); }); // Extra terminating semicolon does not change output assertSingleSequenceElement('\x1b[1;4;m', (child) => { assert(dom.hasClass(child, 'code-bold')); assert(dom.hasClass(child, 'code-underline')); }); // Cancellation code removes multiple codes assertSingleSequenceElement('\x1b[1;4;30;41;32;43;34;45;36;47;0m', (child) => { assert.equal(0, child.classList.length); }); }); /** * Assert that a given ANSI sequence produces the expected number of {@link HTMLSpanElement} children. For * each child, run the provided assertion. * * @param sequence The ANSI sequence to verify. * @param assertions A set of assertions to run on the resulting children. */ function assertMultipleSequenceElements(sequence: string, assertions: Array<(child: HTMLSpanElement) => void>): void { const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector); assert.equal(assertions.length, root.children.length); for (let i = 0; i < assertions.length; i++) { const child: Node = root.children[i]; if (child instanceof HTMLSpanElement) { assertions[i](child); } else { assert.fail('Unexpected assertion error'); } } } test('Expected multiple sequence operation', () => { // Multiple codes affect the same text assertSingleSequenceElement('\x1b[1m\x1b[4m\x1b[32m', (child) => { assert(dom.hasClass(child, 'code-bold')); assert(dom.hasClass(child, 'code-underline')); assert(dom.hasClass(child, 'code-foreground-32')); }); // Consecutive codes do not affect previous ones assertMultipleSequenceElements('\x1b[1mbold\x1b[32mgreen\x1b[4munderline\x1b[0mnothing', [ (bold) => { assert.equal(1, bold.classList.length); assert(dom.hasClass(bold, 'code-bold')); }, (green) => { assert.equal(2, green.classList.length); assert(dom.hasClass(green, 'code-bold')); assert(dom.hasClass(green, 'code-foreground-32')); }, (underline) => { assert.equal(3, underline.classList.length); assert(dom.hasClass(underline, 'code-bold')); assert(dom.hasClass(underline, 'code-foreground-32')); assert(dom.hasClass(underline, 'code-underline')); }, (nothing) => { assert.equal(0, nothing.classList.length); }, ]); }); /** * Assert that the provided ANSI sequence exactly matches the text content of the resulting * {@link HTMLSpanElement}. * * @param sequence The ANSI sequence to verify. */ function assertSequenceEqualToContent(sequence: string): void { const child: HTMLSpanElement = getSequenceOutput(sequence); assert(child.textContent === sequence); } test('Invalid codes treated as regular text', () => { // Individual components of ANSI code start are printed assertSequenceEqualToContent('\x1b'); assertSequenceEqualToContent('['); // Unsupported sequence prints both characters assertSequenceEqualToContent('\x1b['); // Random strings are displayed properly for (let i = 0; i < 50; i++) { const uuid: string = generateUuid(); assertSequenceEqualToContent(uuid); } }); /** * Assert that a given ANSI sequence maintains added content following the ANSI code, and that * the expression itself is thrown away. * * @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes * only, and should not include actual text content as it is provided by this function. */ function assertEmptyOutput(sequence: string) { const child: HTMLSpanElement = getSequenceOutput(sequence + 'content'); assert.equal('content', child.textContent); assert.equal(0, child.classList.length); } test('Empty sequence output', () => { const sequences: string[] = [ // No colour codes '', '\x1b[;m', '\x1b[1;;m', '\x1b[m', // Unsupported colour codes '\x1b[30;50m', '\x1b[99m' ]; sequences.forEach(sequence => { assertEmptyOutput(sequence); }); // Check other possible ANSI terminators const terminators: string[] = 'ABCDHIJKfhmpsu'.split(''); terminators.forEach(terminator => { assertEmptyOutput('\x1b[content' + terminator); }); }); });
src/vs/workbench/parts/debug/test/browser/debugANSIHandling.test.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017747383390087634, 0.0001732810924295336, 0.00016557508206460625, 0.00017394337919540703, 0.000002914952119681402 ]
{ "id": 7, "code_window": [ "\n", "\t// --- outline\n", "\n", "\tregisterDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {\n", "\t\tconst handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension);\n", "\t\tconst displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined;\n", "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst handle = this._addNewAdapter(new DocumentSymbolAdapter(this._documents, provider), extension);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1004 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-fg{fill:#2b282e}.icon-vs-action-blue{fill:#75beff}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M0 10.736V4.5L9 0l7 3.5v6.236l-9 4.5-7-3.5z" id="outline"/><path class="icon-vs-action-blue" d="M9 1L1 5v5l6 3 8-4V4L9 1zM7 6.882L3.236 5 9 2.118 12.764 4 7 6.882z" id="iconBg"/><path class="icon-vs-fg" d="M9 2.118L12.764 4 7 6.882 3.236 5 9 2.118z" id="iconFg"/></svg>
src/vs/editor/contrib/suggest/media/Field_inverse_16x.svg
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00016969107673503458, 0.00016969107673503458, 0.00016969107673503458, 0.00016969107673503458, 0 ]
{ "id": 7, "code_window": [ "\n", "\t// --- outline\n", "\n", "\tregisterDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {\n", "\t\tconst handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension);\n", "\t\tconst displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined;\n", "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst handle = this._addNewAdapter(new DocumentSymbolAdapter(this._documents, provider), extension);\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1004 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CursorColumns, CursorConfiguration, ICursorSimpleModel, SingleCursorState } from 'vs/editor/common/controller/cursorCommon'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; export class CursorPosition { _cursorPositionBrand: void; public readonly lineNumber: number; public readonly column: number; public readonly leftoverVisibleColumns: number; constructor(lineNumber: number, column: number, leftoverVisibleColumns: number) { this.lineNumber = lineNumber; this.column = column; this.leftoverVisibleColumns = leftoverVisibleColumns; } } export class MoveOperations { public static left(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number): CursorPosition { if (column > model.getLineMinColumn(lineNumber)) { if (CursorColumns.isLowSurrogate(model, lineNumber, column - 2)) { // character before column is a low surrogate column = column - 2; } else { column = column - 1; } } else if (lineNumber > 1) { lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } return new CursorPosition(lineNumber, column, 0); } public static moveLeft(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, noOfColumns: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move left without selection cancels selection and puts cursor at the beginning of the selection lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { let r = MoveOperations.left(config, model, cursor.position.lineNumber, cursor.position.column - (noOfColumns - 1)); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } public static right(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number): CursorPosition { if (column < model.getLineMaxColumn(lineNumber)) { if (CursorColumns.isHighSurrogate(model, lineNumber, column - 1)) { // character after column is a high surrogate column = column + 2; } else { column = column + 1; } } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = model.getLineMinColumn(lineNumber); } return new CursorPosition(lineNumber, column, 0); } public static moveRight(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, noOfColumns: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { let r = MoveOperations.right(config, model, cursor.position.lineNumber, cursor.position.column + (noOfColumns - 1)); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } public static down(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number, leftoverVisibleColumns: number, count: number, allowMoveOnLastLine: boolean): CursorPosition { const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; lineNumber = lineNumber + count; let lineCount = model.getLineCount(); if (lineNumber > lineCount) { lineNumber = lineCount; if (allowMoveOnLastLine) { column = model.getLineMaxColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } } else { column = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); return new CursorPosition(lineNumber, column, leftoverVisibleColumns); } public static moveDown(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, linesCount: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move down acts relative to the end of selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } let r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } public static translateDown(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState): SingleCursorState { let selection = cursor.selection; let selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); let position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState( new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns ); } public static up(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number, leftoverVisibleColumns: number, count: number, allowMoveOnFirstLine: boolean): CursorPosition { const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; lineNumber = lineNumber - count; if (lineNumber < 1) { lineNumber = 1; if (allowMoveOnFirstLine) { column = model.getLineMinColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } } else { column = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn); if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) { column = column - 1; } } leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); return new CursorPosition(lineNumber, column, leftoverVisibleColumns); } public static moveUp(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, linesCount: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move up acts relative to the beginning of selection lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } let r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } public static translateUp(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState): SingleCursorState { let selection = cursor.selection; let selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); let position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState( new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns ); } public static moveToBeginningOfLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { let lineNumber = cursor.position.lineNumber; let minColumn = model.getLineMinColumn(lineNumber); let firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn; let column: number; let relevantColumnNumber = cursor.position.column; if (relevantColumnNumber === firstNonBlankColumn) { column = minColumn; } else { column = firstNonBlankColumn; } return cursor.move(inSelectionMode, lineNumber, column, 0); } public static moveToEndOfLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { let lineNumber = cursor.position.lineNumber; let maxColumn = model.getLineMaxColumn(lineNumber); return cursor.move(inSelectionMode, lineNumber, maxColumn, 0); } public static moveToBeginningOfBuffer(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { return cursor.move(inSelectionMode, 1, 1, 0); } public static moveToEndOfBuffer(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { let lastLineNumber = model.getLineCount(); let lastColumn = model.getLineMaxColumn(lastLineNumber); return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0); } }
src/vs/editor/common/controller/cursorMoveOperations.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017629591457080096, 0.00017356770695187151, 0.00016631132166367024, 0.0001735259429551661, 0.0000019825363324343925 ]
{ "id": 8, "code_window": [ "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n", "\t}\n", "\n", "\t$provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> {\n", "\t\treturn this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n", "\t}\n", "\n", "\t// --- code lens\n", "\n", "\tregisterCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn this._withAdapter(handle, DocumentSymbolAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1011 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.41216492652893066, 0.007524121552705765, 0.0001607078593224287, 0.00018502557941246778, 0.04750682786107063 ]
{ "id": 8, "code_window": [ "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n", "\t}\n", "\n", "\t$provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> {\n", "\t\treturn this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n", "\t}\n", "\n", "\t// --- code lens\n", "\n", "\tregisterCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn this._withAdapter(handle, DocumentSymbolAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1011 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { IframeUtils } from 'vs/base/browser/iframe'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; export interface IStandardMouseMoveEventData { leftButton: boolean; posx: number; posy: number; } export interface IEventMerger<R> { (lastEvent: R, currentEvent: MouseEvent): R; } export interface IMouseMoveCallback<R> { (mouseMoveData: R): void; } export interface IOnStopCallback { (): void; } export function standardMouseMoveMerger(lastEvent: IStandardMouseMoveEventData, currentEvent: MouseEvent): IStandardMouseMoveEventData { let ev = new StandardMouseEvent(currentEvent); ev.preventDefault(); return { leftButton: ev.leftButton, posx: ev.posx, posy: ev.posy }; } export class GlobalMouseMoveMonitor<R> extends Disposable { private hooks: IDisposable[]; private mouseMoveEventMerger: IEventMerger<R> | null; private mouseMoveCallback: IMouseMoveCallback<R> | null; private onStopCallback: IOnStopCallback | null; constructor() { super(); this.hooks = []; this.mouseMoveEventMerger = null; this.mouseMoveCallback = null; this.onStopCallback = null; } public dispose(): void { this.stopMonitoring(false); super.dispose(); } public stopMonitoring(invokeStopCallback: boolean): void { if (!this.isMonitoring()) { // Not monitoring return; } // Unhook this.hooks = dispose(this.hooks); this.mouseMoveEventMerger = null; this.mouseMoveCallback = null; let onStopCallback = this.onStopCallback; this.onStopCallback = null; if (invokeStopCallback && onStopCallback) { onStopCallback(); } } public isMonitoring() { return this.hooks.length > 0; } public startMonitoring( mouseMoveEventMerger: IEventMerger<R>, mouseMoveCallback: IMouseMoveCallback<R>, onStopCallback: IOnStopCallback ): void { if (this.isMonitoring()) { // I am already hooked return; } this.mouseMoveEventMerger = mouseMoveEventMerger; this.mouseMoveCallback = mouseMoveCallback; this.onStopCallback = onStopCallback; let windowChain = IframeUtils.getSameOriginWindowChain(); for (const element of windowChain) { this.hooks.push(dom.addDisposableThrottledListener(element.window.document, 'mousemove', (data: R) => this.mouseMoveCallback!(data), (lastEvent: R, currentEvent) => this.mouseMoveEventMerger!(lastEvent, currentEvent as MouseEvent) )); this.hooks.push(dom.addDisposableListener(element.window.document, 'mouseup', (e: MouseEvent) => this.stopMonitoring(true))); } if (IframeUtils.hasDifferentOriginAncestor()) { let lastSameOriginAncestor = windowChain[windowChain.length - 1]; // We might miss a mouse up if it happens outside the iframe // This one is for Chrome this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseout', (browserEvent: MouseEvent) => { let e = new StandardMouseEvent(browserEvent); if (e.target.tagName.toLowerCase() === 'html') { this.stopMonitoring(true); } })); // This one is for FF this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseover', (browserEvent: MouseEvent) => { let e = new StandardMouseEvent(browserEvent); if (e.target.tagName.toLowerCase() === 'html') { this.stopMonitoring(true); } })); // This one is for IE this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', (browserEvent: MouseEvent) => { this.stopMonitoring(true); })); } } }
src/vs/base/browser/globalMouseMoveMonitor.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017613913223613054, 0.00017200253205373883, 0.00016745463653933257, 0.0001726806949591264, 0.00000319802916237677 ]
{ "id": 8, "code_window": [ "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n", "\t}\n", "\n", "\t$provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> {\n", "\t\treturn this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n", "\t}\n", "\n", "\t// --- code lens\n", "\n", "\tregisterCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn this._withAdapter(handle, DocumentSymbolAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1011 }
test/** src/** out/** tsconfig.json extension.webpack.config.js CONTRIBUTING.md cgmanifest.json yarn.lock
extensions/emmet/.vscodeignore
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017285498324781656, 0.00017285498324781656, 0.00017285498324781656, 0.00017285498324781656, 0 ]
{ "id": 8, "code_window": [ "\t\tthis._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName);\n", "\t\treturn this._createDisposable(handle);\n", "\t}\n", "\n", "\t$provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> {\n", "\t\treturn this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n", "\t}\n", "\n", "\t// --- code lens\n", "\n", "\tregisterCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn this._withAdapter(handle, DocumentSymbolAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token));\n" ], "file_path": "src/vs/workbench/api/node/extHostLanguageFeatures.ts", "type": "replace", "edit_start_line_idx": 1011 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import { ShiftCommand } from 'vs/editor/common/commands/shiftCommand'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand, ICursorStateComputerData, IEditOperationBuilder } from 'vs/editor/common/editorCommon'; import { ITextModel } from 'vs/editor/common/model'; import { IndentAction } from 'vs/editor/common/modes/languageConfiguration'; import { IIndentConverter, LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { IndentConsts } from 'vs/editor/common/modes/supports/indentRules'; import * as indentUtils from 'vs/editor/contrib/indentation/indentUtils'; export class MoveLinesCommand implements ICommand { private _selection: Selection; private _isMovingDown: boolean; private _autoIndent: boolean; private _selectionId: string; private _moveEndPositionDown: boolean; private _moveEndLineSelectionShrink: boolean; constructor(selection: Selection, isMovingDown: boolean, autoIndent: boolean) { this._selection = selection; this._isMovingDown = isMovingDown; this._autoIndent = autoIndent; this._moveEndLineSelectionShrink = false; } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { let modelLineCount = model.getLineCount(); if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) { return; } if (!this._isMovingDown && this._selection.startLineNumber === 1) { return; } this._moveEndPositionDown = false; let s = this._selection; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { this._moveEndPositionDown = true; s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1)); } let tabSize = model.getOptions().tabSize; let insertSpaces = model.getOptions().insertSpaces; let indentConverter = this.buildIndentConverter(tabSize); let virtualModel = { getLineTokens: (lineNumber: number) => { return model.getLineTokens(lineNumber); }, getLanguageIdentifier: () => { return model.getLanguageIdentifier(); }, getLanguageIdAtPosition: (lineNumber: number, column: number) => { return model.getLanguageIdAtPosition(lineNumber, column); }, getLineContent: null as unknown as (lineNumber: number) => string, }; if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) { // Current line is empty let lineNumber = s.startLineNumber; let otherLineNumber = (this._isMovingDown ? lineNumber + 1 : lineNumber - 1); if (model.getLineMaxColumn(otherLineNumber) === 1) { // Other line number is empty too, so no editing is needed // Add a no-op to force running by the model builder.addEditOperation(new Range(1, 1, 1, 1), null); } else { // Type content from other line number on line number builder.addEditOperation(new Range(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber)); // Remove content from other line number builder.addEditOperation(new Range(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null); } // Track selection at the other line number s = new Selection(otherLineNumber, 1, otherLineNumber, 1); } else { let movingLineNumber: number; let movingLineText: string; if (this._isMovingDown) { movingLineNumber = s.endLineNumber + 1; movingLineText = model.getLineContent(movingLineNumber); // Delete line that needs to be moved builder.addEditOperation(new Range(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null); let insertingText = movingLineText; if (this.shouldAutoIndent(model, s)) { let movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1); // if s.startLineNumber - 1 matches onEnter rule, we still honor that. if (movingLineMatchResult !== null) { let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber)); let newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize); let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); insertingText = newIndentation + this.trimLeft(movingLineText); } else { // no enter rule matches, let's check indentatin rules then. virtualModel.getLineContent = (lineNumber: number) => { if (lineNumber === s.startLineNumber) { return model.getLineContent(movingLineNumber); } else { return model.getLineContent(lineNumber); } }; let indentOfMovingLine = LanguageConfigurationRegistry.getGoodIndentForLine(virtualModel, model.getLanguageIdAtPosition( movingLineNumber, 1), s.startLineNumber, indentConverter); if (indentOfMovingLine !== null) { let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber)); let newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize); let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); if (newSpaceCnt !== oldSpaceCnt) { let newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces); insertingText = newIndentation + this.trimLeft(movingLineText); } } } // add edit operations for moving line first to make sure it's executed after we make indentation change // to s.startLineNumber builder.addEditOperation(new Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n'); let ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber, insertingText); // check if the line being moved before matches onEnter rules, if so let's adjust the indentation by onEnter rules. if (ret !== null) { if (ret !== 0) { this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret); } } else { // it doesn't match onEnter rules, let's check indentation rules then. virtualModel.getLineContent = (lineNumber: number) => { if (lineNumber === s.startLineNumber) { return insertingText; } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) { return model.getLineContent(lineNumber - 1); } else { return model.getLineContent(lineNumber); } }; let newIndentatOfMovingBlock = LanguageConfigurationRegistry.getGoodIndentForLine(virtualModel, model.getLanguageIdAtPosition( movingLineNumber, 1), s.startLineNumber + 1, indentConverter); if (newIndentatOfMovingBlock !== null) { const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); const newSpaceCnt = indentUtils.getSpaceCnt(newIndentatOfMovingBlock, tabSize); const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); if (newSpaceCnt !== oldSpaceCnt) { const spaceCntOffset = newSpaceCnt - oldSpaceCnt; this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset); } } } } else { // Insert line that needs to be moved before builder.addEditOperation(new Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n'); } } else { movingLineNumber = s.startLineNumber - 1; movingLineText = model.getLineContent(movingLineNumber); // Delete line that needs to be moved builder.addEditOperation(new Range(movingLineNumber, 1, movingLineNumber + 1, 1), null); // Insert line that needs to be moved after builder.addEditOperation(new Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + movingLineText); if (this.shouldAutoIndent(model, s)) { virtualModel.getLineContent = (lineNumber: number) => { if (lineNumber === movingLineNumber) { return model.getLineContent(s.startLineNumber); } else { return model.getLineContent(lineNumber); } }; let ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2); // check if s.startLineNumber - 2 matches onEnter rules, if so adjust the moving block by onEnter rules. if (ret !== null) { if (ret !== 0) { this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret); } } else { // it doesn't match any onEnter rule, let's check indentation rules then. let indentOfFirstLine = LanguageConfigurationRegistry.getGoodIndentForLine(virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter); if (indentOfFirstLine !== null) { // adjust the indentation of the moving block let oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber)); let newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize); let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize); if (newSpaceCnt !== oldSpaceCnt) { let spaceCntOffset = newSpaceCnt - oldSpaceCnt; this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset); } } } } } } this._selectionId = builder.trackSelection(s); } private buildIndentConverter(tabSize: number): IIndentConverter { return { shiftIndent: (indentation) => { let desiredIndentCount = ShiftCommand.shiftIndentCount(indentation, indentation.length + 1, tabSize); let newIndentation = ''; for (let i = 0; i < desiredIndentCount; i++) { newIndentation += '\t'; } return newIndentation; }, unshiftIndent: (indentation) => { let desiredIndentCount = ShiftCommand.unshiftIndentCount(indentation, indentation.length + 1, tabSize); let newIndentation = ''; for (let i = 0; i < desiredIndentCount; i++) { newIndentation += '\t'; } return newIndentation; } }; } private matchEnterRule(model: ITextModel, indentConverter: IIndentConverter, tabSize: number, line: number, oneLineAbove: number, oneLineAboveText?: string) { let validPrecedingLine = oneLineAbove; while (validPrecedingLine >= 1) { // ship empty lines as empty lines just inherit indentation let lineContent; if (validPrecedingLine === oneLineAbove && oneLineAboveText !== undefined) { lineContent = oneLineAboveText; } else { lineContent = model.getLineContent(validPrecedingLine); } let nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent); if (nonWhitespaceIdx >= 0) { break; } validPrecedingLine--; } if (validPrecedingLine < 1 || line > model.getLineCount()) { return null; } let maxColumn = model.getLineMaxColumn(validPrecedingLine); let enter = LanguageConfigurationRegistry.getEnterAction(model, new Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn)); if (enter) { let enterPrefix = enter.indentation; let enterAction = enter.enterAction; if (enterAction.indentAction === IndentAction.None) { enterPrefix = enter.indentation + enterAction.appendText; } else if (enterAction.indentAction === IndentAction.Indent) { enterPrefix = enter.indentation + enterAction.appendText; } else if (enterAction.indentAction === IndentAction.IndentOutdent) { enterPrefix = enter.indentation; } else if (enterAction.indentAction === IndentAction.Outdent) { enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enterAction.appendText; } let movingLineText = model.getLineContent(line); if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) { let oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line)); let newIndentation = strings.getLeadingWhitespace(enterPrefix); let indentMetadataOfMovelingLine = LanguageConfigurationRegistry.getIndentMetadata(model, line); if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & IndentConsts.DECREASE_MASK) { newIndentation = indentConverter.unshiftIndent(newIndentation); } let newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize); let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize); return newSpaceCnt - oldSpaceCnt; } } return null; } private trimLeft(str: string) { return str.replace(/^\s+/, ''); } private shouldAutoIndent(model: ITextModel, selection: Selection) { if (!this._autoIndent) { return false; } // if it's not easy to tokenize, we stop auto indent. if (!model.isCheapToTokenize(selection.startLineNumber)) { return false; } let languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1); let languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1); if (languageAtSelectionStart !== languageAtSelectionEnd) { return false; } if (LanguageConfigurationRegistry.getIndentRulesSupport(languageAtSelectionStart) === null) { return false; } return true; } private getIndentEditsOfMovingBlock(model: ITextModel, builder: IEditOperationBuilder, s: Selection, tabSize: number, insertSpaces: boolean, offset: number) { for (let i = s.startLineNumber; i <= s.endLineNumber; i++) { let lineContent = model.getLineContent(i); let originalIndent = strings.getLeadingWhitespace(lineContent); let originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize); let newSpacesCnt = originalSpacesCnt + offset; let newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces); if (newIndent !== originalIndent) { builder.addEditOperation(new Range(i, 1, i, originalIndent.length + 1), newIndent); if (i === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === '') { // as users select part of the original indent white spaces // when we adjust the indentation of endLine, we should adjust the cursor position as well. this._moveEndLineSelectionShrink = true; } } } } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { let result = helper.getTrackedSelection(this._selectionId); if (this._moveEndPositionDown) { result = result.setEndPosition(result.endLineNumber + 1, 1); } if (this._moveEndLineSelectionShrink && result.startLineNumber < result.endLineNumber) { result = result.setEndPosition(result.endLineNumber, 2); } return result; } }
src/vs/editor/contrib/linesOperations/moveLinesCommand.ts
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017736994777806103, 0.0001742442836984992, 0.00016055331798270345, 0.0001752735988702625, 0.000003015892616531346 ]
{ "id": 9, "code_window": [ "export namespace DocumentSymbol {\n", "\texport function from(info: vscode.DocumentSymbol): modes.DocumentSymbol {\n", "\t\tconst result: modes.DocumentSymbol = {\n", "\t\t\tname: info.name,\n", "\t\t\tdetail: info.detail,\n", "\t\t\trange: Range.from(info.range),\n", "\t\t\tselectionRange: Range.from(info.selectionRange),\n", "\t\t\tkind: SymbolKind.from(info.kind)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostTypeConverters.ts", "type": "replace", "edit_start_line_idx": 545 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from 'vs/base/common/uri'; import { mixin } from 'vs/base/common/objects'; import * as vscode from 'vscode'; import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters'; import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, DocumentSymbol } from 'vs/workbench/api/node/extHostTypes'; import { ISingleEditOperation } from 'vs/editor/common/model'; import * as modes from 'vs/editor/common/modes'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/node/extHostCommands'; import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics'; import { asPromise } from 'vs/base/common/async'; import { MainContext, MainThreadLanguageFeaturesShape, ExtHostLanguageFeaturesShape, ObjectIdentifier, IRawColorInfo, IMainContext, IdObject, ISerializedRegExp, ISerializedIndentationRule, ISerializedOnEnterRule, ISerializedLanguageConfiguration, WorkspaceSymbolDto, SuggestResultDto, WorkspaceSymbolsDto, SuggestionDto, CodeActionDto, ISerializedDocumentFilter, WorkspaceEditDto, ISerializedSignatureHelpProviderMetadata } from './extHost.protocol'; import { regExpLeadsToEndlessLoop, regExpFlags } from 'vs/base/common/strings'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange, Range as EditorRange } from 'vs/editor/common/core/range'; import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays'; import { isObject } from 'vs/base/common/types'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; // --- adapter class OutlineAdapter { private _documents: ExtHostDocuments; private _provider: vscode.DocumentSymbolProvider; constructor(documents: ExtHostDocuments, provider: vscode.DocumentSymbolProvider) { this._documents = documents; this._provider = provider; } provideDocumentSymbols(resource: URI, token: CancellationToken): Promise<modes.DocumentSymbol[]> { let doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentSymbols(doc, token)).then(value => { if (isFalsyOrEmpty(value)) { return undefined; } if (value[0] instanceof DocumentSymbol) { return (<DocumentSymbol[]>value).map(typeConvert.DocumentSymbol.from); } else { return OutlineAdapter._asDocumentSymbolTree(resource, <SymbolInformation[]>value); } }); } private static _asDocumentSymbolTree(resource: URI, infos: SymbolInformation[]): modes.DocumentSymbol[] { // first sort by start (and end) and then loop over all elements // and build a tree based on containment. infos = infos.slice(0).sort((a, b) => { let res = a.location.range.start.compareTo(b.location.range.start); if (res === 0) { res = b.location.range.end.compareTo(a.location.range.end); } return res; }); let res: modes.DocumentSymbol[] = []; let parentStack: modes.DocumentSymbol[] = []; for (const info of infos) { let element = <modes.DocumentSymbol>{ name: info.name, kind: typeConvert.SymbolKind.from(info.kind), containerName: info.containerName, range: typeConvert.Range.from(info.location.range), selectionRange: typeConvert.Range.from(info.location.range), children: [] }; while (true) { if (parentStack.length === 0) { parentStack.push(element); res.push(element); break; } let parent = parentStack[parentStack.length - 1]; if (EditorRange.containsRange(parent.range, element.range) && !EditorRange.equalsRange(parent.range, element.range)) { parent.children.push(element); parentStack.push(element); break; } parentStack.pop(); } } return res; } } class CodeLensAdapter { private static _badCmd: vscode.Command = { command: 'missing', title: '<<MISSING COMMAND>>' }; constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.CodeLensProvider ) { } provideCodeLenses(resource: URI, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideCodeLenses(doc, token)).then(lenses => { if (Array.isArray(lenses)) { return lenses.map(lens => { const id = this._heapService.keep(lens); return ObjectIdentifier.mixin({ range: typeConvert.Range.from(lens.range), command: this._commands.toInternal(lens.command) }, id); }); } return undefined; }); } resolveCodeLens(resource: URI, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { const lens = this._heapService.get<vscode.CodeLens>(ObjectIdentifier.of(symbol)); if (!lens) { return undefined; } let resolve: Promise<vscode.CodeLens>; if (typeof this._provider.resolveCodeLens !== 'function' || lens.isResolved) { resolve = Promise.resolve(lens); } else { resolve = asPromise(() => this._provider.resolveCodeLens(lens, token)); } return resolve.then(newLens => { newLens = newLens || lens; symbol.command = this._commands.toInternal(newLens.command || CodeLensAdapter._badCmd); return symbol; }); } } function convertToDefinitionLinks(value: vscode.Definition): modes.DefinitionLink[] { if (Array.isArray(value)) { return (value as (vscode.DefinitionLink | vscode.Location)[]).map(typeConvert.DefinitionLink.from); } else if (value) { return [typeConvert.DefinitionLink.from(value)]; } return undefined; } class DefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DefinitionProvider ) { } provideDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class DeclarationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DeclarationProvider ) { } provideDeclaration(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDeclaration(doc, pos, token)).then(convertToDefinitionLinks); } } class ImplementationAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ImplementationProvider ) { } provideImplementation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideImplementation(doc, pos, token)).then(convertToDefinitionLinks); } } class TypeDefinitionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.TypeDefinitionProvider ) { } provideTypeDefinition(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideTypeDefinition(doc, pos, token)).then(convertToDefinitionLinks); } } class HoverAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.HoverProvider, ) { } public provideHover(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.Hover> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideHover(doc, pos, token)).then(value => { if (!value || isFalsyOrEmpty(value.contents)) { return undefined; } if (!value.range) { value.range = doc.getWordRangeAtPosition(pos); } if (!value.range) { value.range = new Range(pos, pos); } return typeConvert.Hover.from(value); }); } } class DocumentHighlightAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentHighlightProvider ) { } provideDocumentHighlights(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.DocumentHighlight.from); } return undefined; }); } } class ReferenceAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.ReferenceProvider ) { } provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideReferences(doc, pos, context, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.location.from); } return undefined; }); } } export interface CustomCodeAction extends CodeActionDto { _isSynthetic?: boolean; } class CodeActionAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _diagnostics: ExtHostDiagnostics, private readonly _provider: vscode.CodeActionProvider, private readonly _logService: ILogService, private readonly _extensionId: ExtensionIdentifier ) { } provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { const doc = this._documents.getDocumentData(resource).document; const ran = Selection.isISelection(rangeOrSelection) ? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection) : <vscode.Range>typeConvert.Range.to(rangeOrSelection); const allDiagnostics: vscode.Diagnostic[] = []; for (const diagnostic of this._diagnostics.getDiagnostics(resource)) { if (ran.intersection(diagnostic.range)) { allDiagnostics.push(diagnostic); } } const codeActionContext: vscode.CodeActionContext = { diagnostics: allDiagnostics, only: context.only ? new CodeActionKind(context.only) : undefined }; return asPromise(() => this._provider.provideCodeActions(doc, ran, codeActionContext, token)).then(commandsOrActions => { if (isFalsyOrEmpty(commandsOrActions)) { return undefined; } const result: CustomCodeAction[] = []; for (const candidate of commandsOrActions) { if (!candidate) { continue; } if (CodeActionAdapter._isCommand(candidate)) { // old school: synthetic code action result.push({ _isSynthetic: true, title: candidate.title, command: this._commands.toInternal(candidate), }); } else { if (codeActionContext.only) { if (!candidate.kind) { this._logService.warn(`${this._extensionId.value} - Code actions of kind '${codeActionContext.only.value} 'requested but returned code action does not have a 'kind'. Code action will be dropped. Please set 'CodeAction.kind'.`); } else if (!codeActionContext.only.contains(candidate.kind)) { this._logService.warn(`${this._extensionId.value} -Code actions of kind '${codeActionContext.only.value} 'requested but returned code action is of kind '${candidate.kind.value}'. Code action will be dropped. Please check 'CodeActionContext.only' to only return requested code actions.`); } } // new school: convert code action result.push({ title: candidate.title, command: candidate.command && this._commands.toInternal(candidate.command), diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from), edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit), kind: candidate.kind && candidate.kind.value }); } } return result; }); } private static _isCommand(thing: any): thing is vscode.Command { return typeof (<vscode.Command>thing).command === 'string' && typeof (<vscode.Command>thing).title === 'string'; } } class DocumentFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentFormattingEditProvider ) { } provideDocumentFormattingEdits(resource: URI, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); return asPromise(() => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class RangeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.DocumentRangeFormattingEditProvider ) { } provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const ran = typeConvert.Range.to(range); return asPromise(() => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class OnTypeFormattingAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.OnTypeFormattingEditProvider ) { } autoFormatTriggerCharacters: string[] = []; // not here provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => { if (Array.isArray(value)) { return value.map(typeConvert.TextEdit.from); } return undefined; }); } } class NavigateTypeAdapter { private readonly _symbolCache: { [id: number]: vscode.SymbolInformation } = Object.create(null); private readonly _resultCache: { [id: number]: [number, number] } = Object.create(null); private readonly _provider: vscode.WorkspaceSymbolProvider; constructor(provider: vscode.WorkspaceSymbolProvider) { this._provider = provider; } provideWorkspaceSymbols(search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { const result: WorkspaceSymbolsDto = IdObject.mixin({ symbols: [] }); return asPromise(() => this._provider.provideWorkspaceSymbols(search, token)).then(value => { if (isNonEmptyArray(value)) { for (const item of value) { if (!item) { // drop continue; } if (!item.name) { console.warn('INVALID SymbolInformation, lacks name', item); continue; } const symbol = IdObject.mixin(typeConvert.WorkspaceSymbol.from(item)); this._symbolCache[symbol._id] = item; result.symbols.push(symbol); } } }).then(() => { if (result.symbols.length > 0) { this._resultCache[result._id] = [result.symbols[0]._id, result.symbols[result.symbols.length - 1]._id]; } return result; }); } resolveWorkspaceSymbol(symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { if (typeof this._provider.resolveWorkspaceSymbol !== 'function') { return Promise.resolve(symbol); } const item = this._symbolCache[symbol._id]; if (item) { return asPromise(() => this._provider.resolveWorkspaceSymbol(item, token)).then(value => { return value && mixin(symbol, typeConvert.WorkspaceSymbol.from(value), true); }); } return undefined; } releaseWorkspaceSymbols(id: number): any { const range = this._resultCache[id]; if (range) { for (let [from, to] = range; from <= to; from++) { delete this._symbolCache[from]; } delete this._resultCache[id]; } } } class RenameAdapter { static supportsResolving(provider: vscode.RenameProvider): boolean { return typeof provider.prepareRename === 'function'; } constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.RenameProvider ) { } provideRenameEdits(resource: URI, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => { if (!value) { return undefined; } return typeConvert.WorkspaceEdit.from(value); }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <WorkspaceEditDto>{ rejectReason, edits: undefined }; } else { // generic error return Promise.reject<WorkspaceEditDto>(err); } }); } resolveRenameLocation(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation & modes.Rejection> { if (typeof this._provider.prepareRename !== 'function') { return Promise.resolve(undefined); } let doc = this._documents.getDocumentData(resource).document; let pos = typeConvert.Position.to(position); return asPromise(() => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => { let range: vscode.Range; let text: string; if (Range.isRange(rangeOrLocation)) { range = rangeOrLocation; text = doc.getText(rangeOrLocation); } else if (isObject(rangeOrLocation)) { range = rangeOrLocation.range; text = rangeOrLocation.placeholder; } if (!range) { return undefined; } if (range.start.line > pos.line || range.end.line < pos.line) { console.warn('INVALID rename location: position line must be within range start/end lines'); return undefined; } return { range: typeConvert.Range.from(range), text }; }, err => { let rejectReason = RenameAdapter._asMessage(err); if (rejectReason) { return <modes.RenameLocation & modes.Rejection>{ rejectReason, range: undefined, text: undefined }; } else { return Promise.reject(err); } }); } private static _asMessage(err: any): string { if (typeof err === 'string') { return err; } else if (err instanceof Error && typeof err.message === 'string') { return err.message; } else { return undefined; } } } class SuggestAdapter { static supportsResolving(provider: vscode.CompletionItemProvider): boolean { return typeof provider.resolveCompletionItem === 'function'; } private _documents: ExtHostDocuments; private _commands: CommandsConverter; private _provider: vscode.CompletionItemProvider; private _cache = new Map<number, vscode.CompletionItem[]>(); private _idPool = 0; constructor(documents: ExtHostDocuments, commands: CommandsConverter, provider: vscode.CompletionItemProvider) { this._documents = documents; this._commands = commands; this._provider = provider; } provideCompletionItems(resource: URI, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise<vscode.CompletionItem[] | vscode.CompletionList>( () => this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.to(context)) ).then(value => { const _id = this._idPool++; const result: SuggestResultDto = { _id, suggestions: [], }; let list: CompletionList; if (!value) { // undefined and null are valid results return undefined; } else if (Array.isArray(value)) { list = new CompletionList(value); } else { list = value; result.incomplete = list.isIncomplete; } // the default text edit range const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)) .with({ end: pos }); for (let i = 0; i < list.items.length; i++) { const suggestion = this._convertCompletionItem(list.items[i], pos, wordRangeBeforePos, i, _id); // check for bad completion item // for the converter did warn if (suggestion) { result.suggestions.push(suggestion); } } this._cache.set(_id, list.items); return result; }); } resolveCompletionItem(resource: URI, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { if (typeof this._provider.resolveCompletionItem !== 'function') { return Promise.resolve(suggestion); } const { _parentId, _id } = (<SuggestionDto>suggestion); const item = this._cache.has(_parentId) && this._cache.get(_parentId)[_id]; if (!item) { return Promise.resolve(suggestion); } return asPromise(() => this._provider.resolveCompletionItem(item, token)).then(resolvedItem => { if (!resolvedItem) { return suggestion; } const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos }); const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId); if (newSuggestion) { mixin(suggestion, newSuggestion, true); } return suggestion; }); } releaseCompletionItems(id: number): any { this._cache.delete(id); } private _convertCompletionItem(item: vscode.CompletionItem, position: vscode.Position, defaultRange: vscode.Range, _id: number, _parentId: number): SuggestionDto { if (typeof item.label !== 'string' || item.label.length === 0) { console.warn('INVALID text edit -> must have at least a label'); return undefined; } const result: SuggestionDto = { // _id, _parentId, // label: item.label, kind: typeConvert.CompletionItemKind.from(item.kind), detail: item.detail, documentation: typeConvert.MarkdownString.fromStrict(item.documentation), filterText: item.filterText, sortText: item.sortText, preselect: item.preselect, // range: undefined, insertText: undefined, insertTextRules: item.keepWhitespace ? modes.CompletionItemInsertTextRule.KeepWhitespace : 0, additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from), command: this._commands.toInternal(item.command), commitCharacters: item.commitCharacters }; // 'insertText'-logic if (item.textEdit) { result.insertText = item.textEdit.newText; } else if (typeof item.insertText === 'string') { result.insertText = item.insertText; } else if (item.insertText instanceof SnippetString) { result.insertText = item.insertText.value; result.insertTextRules += modes.CompletionItemInsertTextRule.InsertAsSnippet; } else { result.insertText = item.label; } // 'overwrite[Before|After]'-logic let range: vscode.Range; if (item.textEdit) { range = item.textEdit.range; } else if (item.range) { range = item.range; } else { range = defaultRange; } result.range = typeConvert.Range.from(range); if (!range.isSingleLine || range.start.line !== position.line) { console.warn('INVALID text edit -> must be single line and on the same line'); return undefined; } return result; } } class SignatureHelpAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SignatureHelpProvider ) { } provideSignatureHelp(resource: URI, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { const doc = this._documents.getDocumentData(resource).document; const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSignatureHelp(doc, pos, token, context)).then(value => { if (value) { return typeConvert.SignatureHelp.from(value); } return undefined; }); } } class LinkProviderAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _heapService: ExtHostHeapService, private readonly _provider: vscode.DocumentLinkProvider ) { } provideLinks(resource: URI, token: CancellationToken): Promise<modes.ILink[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentLinks(doc, token)).then(links => { if (!Array.isArray(links)) { return undefined; } const result: modes.ILink[] = []; for (const link of links) { let data = typeConvert.DocumentLink.from(link); let id = this._heapService.keep(link); ObjectIdentifier.mixin(data, id); result.push(data); } return result; }); } resolveLink(link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { if (typeof this._provider.resolveDocumentLink !== 'function') { return undefined; } const id = ObjectIdentifier.of(link); const item = this._heapService.get<vscode.DocumentLink>(id); if (!item) { return undefined; } return asPromise(() => this._provider.resolveDocumentLink(item, token)).then(value => { if (value) { return typeConvert.DocumentLink.from(value); } return undefined; }); } } class ColorProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.DocumentColorProvider ) { } provideColors(resource: URI, token: CancellationToken): Promise<IRawColorInfo[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideDocumentColors(doc, token)).then(colors => { if (!Array.isArray(colors)) { return []; } const colorInfos: IRawColorInfo[] = colors.map(ci => { return { color: typeConvert.Color.from(ci.color), range: typeConvert.Range.from(ci.range) }; }); return colorInfos; }); } provideColorPresentations(resource: URI, raw: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { const document = this._documents.getDocumentData(resource).document; const range = typeConvert.Range.to(raw.range); const color = typeConvert.Color.to(raw.color); return asPromise(() => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => { return value.map(typeConvert.ColorPresentation.from); }); } } class FoldingProviderAdapter { constructor( private _documents: ExtHostDocuments, private _provider: vscode.FoldingRangeProvider ) { } provideFoldingRanges(resource: URI, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { const doc = this._documents.getDocumentData(resource).document; return asPromise(() => this._provider.provideFoldingRanges(doc, context, token)).then(ranges => { if (!Array.isArray(ranges)) { return undefined; } return ranges.map(typeConvert.FoldingRange.from); }); } } class SelectionRangeAdapter { constructor( private readonly _documents: ExtHostDocuments, private readonly _provider: vscode.SelectionRangeProvider ) { } provideSelectionRanges(resource: URI, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { const { document } = this._documents.getDocumentData(resource); const pos = typeConvert.Position.to(position); return asPromise(() => this._provider.provideSelectionRanges(document, pos, token)).then(selectionRanges => { if (isFalsyOrEmpty(selectionRanges)) { return undefined; } let result: modes.SelectionRange[] = []; let last: vscode.Position | vscode.Range = pos; for (const sel of selectionRanges) { if (!sel.range.contains(last)) { throw new Error('INVALID selection range, must contain the previous range'); } result.push(typeConvert.SelectionRange.from(sel)); last = sel.range; } return result; }); } } type Adapter = OutlineAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter | SuggestAdapter | SignatureHelpAdapter | LinkProviderAdapter | ImplementationAdapter | TypeDefinitionAdapter | ColorProviderAdapter | FoldingProviderAdapter | DeclarationAdapter | SelectionRangeAdapter; class AdapterData { constructor( readonly adapter: Adapter, readonly extension: IExtensionDescription | undefined ) { } } export interface ISchemeTransformer { transformOutgoing(scheme: string): string; } export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape { private static _handlePool: number = 0; private readonly _schemeTransformer: ISchemeTransformer; private _proxy: MainThreadLanguageFeaturesShape; private _documents: ExtHostDocuments; private _commands: ExtHostCommands; private _heapService: ExtHostHeapService; private _diagnostics: ExtHostDiagnostics; private _adapter = new Map<number, AdapterData>(); private readonly _logService: ILogService; constructor( mainContext: IMainContext, schemeTransformer: ISchemeTransformer, documents: ExtHostDocuments, commands: ExtHostCommands, heapMonitor: ExtHostHeapService, diagnostics: ExtHostDiagnostics, logService: ILogService ) { this._schemeTransformer = schemeTransformer; this._proxy = mainContext.getProxy(MainContext.MainThreadLanguageFeatures); this._documents = documents; this._commands = commands; this._heapService = heapMonitor; this._diagnostics = diagnostics; this._logService = logService; } private _transformDocumentSelector(selector: vscode.DocumentSelector): ISerializedDocumentFilter[] { if (Array.isArray(selector)) { return selector.map(sel => this._doTransformDocumentSelector(sel)); } return [this._doTransformDocumentSelector(selector)]; } private _doTransformDocumentSelector(selector: string | vscode.DocumentFilter): ISerializedDocumentFilter { if (typeof selector === 'string') { return { $serialized: true, language: selector }; } if (selector) { return { $serialized: true, language: selector.language, scheme: this._transformScheme(selector.scheme), pattern: selector.pattern, exclusive: selector.exclusive }; } return undefined; } private _transformScheme(scheme: string): string { if (this._schemeTransformer && typeof scheme === 'string') { return this._schemeTransformer.transformOutgoing(scheme); } return scheme; } private _createDisposable(handle: number): Disposable { return new Disposable(() => { this._adapter.delete(handle); this._proxy.$unregister(handle); }); } private _nextHandle(): number { return ExtHostLanguageFeatures._handlePool++; } private _withAdapter<A, R>(handle: number, ctor: { new(...args: any[]): A }, callback: (adapter: A) => Promise<R>): Promise<R> { let data = this._adapter.get(handle); if (data.adapter instanceof ctor) { let t1: number; if (data.extension) { t1 = Date.now(); this._logService.trace(`[${data.extension.identifier.value}] INVOKE provider '${(ctor as any).name}'`); } let p = callback(data.adapter); if (data.extension) { Promise.resolve(p).then( () => this._logService.trace(`[${data.extension.identifier.value}] provider DONE after ${Date.now() - t1}ms`), err => { this._logService.error(`[${data.extension.identifier.value}] provider FAILED`); this._logService.error(err); } ); } return p; } return Promise.reject(new Error('no adapter found')); } private _addNewAdapter(adapter: Adapter, extension: IExtensionDescription): number { const handle = this._nextHandle(); this._adapter.set(handle, new AdapterData(adapter, extension)); return handle; } // --- outline registerDocumentSymbolProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider), extension); const displayName = (metadata && metadata.label) || (extension && (extension.displayName || extension.name)) || undefined; this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), displayName); return this._createDisposable(handle); } $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[]> { return this._withAdapter(handle, OutlineAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token)); } // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { const handle = this._nextHandle(); const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this._nextHandle() : undefined; this._adapter.set(handle, new AdapterData(new CodeLensAdapter(this._documents, this._commands.converter, this._heapService, provider), extension)); this._proxy.$registerCodeLensSupport(handle, this._transformDocumentSelector(selector), eventHandle); let result = this._createDisposable(handle); if (eventHandle !== undefined) { const subscription = provider.onDidChangeCodeLenses(_ => this._proxy.$emitCodeLensEvent(eventHandle)); result = Disposable.from(result, subscription); } return result; } $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ICodeLensSymbol[]> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource), token)); } $resolveCodeLens(handle: number, resource: UriComponents, symbol: modes.ICodeLensSymbol, token: CancellationToken): Promise<modes.ICodeLensSymbol> { return this._withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol, token)); } // --- declaration registerDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new DefinitionAdapter(this._documents, provider), extension); this._proxy.$registerDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DefinitionAdapter, adapter => adapter.provideDefinition(URI.revive(resource), position, token)); } registerDeclarationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable { const handle = this._addNewAdapter(new DeclarationAdapter(this._documents, provider), extension); this._proxy.$registerDeclarationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, DeclarationAdapter, adapter => adapter.provideDeclaration(URI.revive(resource), position, token)); } registerImplementationProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable { const handle = this._addNewAdapter(new ImplementationAdapter(this._documents, provider), extension); this._proxy.$registerImplementationSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, ImplementationAdapter, adapter => adapter.provideImplementation(URI.revive(resource), position, token)); } registerTypeDefinitionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable { const handle = this._addNewAdapter(new TypeDefinitionAdapter(this._documents, provider), extension); this._proxy.$registerTypeDefinitionSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DefinitionLink[]> { return this._withAdapter(handle, TypeDefinitionAdapter, adapter => adapter.provideTypeDefinition(URI.revive(resource), position, token)); } // --- extra info registerHoverProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.HoverProvider, extensionId?: ExtensionIdentifier): vscode.Disposable { const handle = this._addNewAdapter(new HoverAdapter(this._documents, provider), extension); this._proxy.$registerHoverProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover> { return this._withAdapter(handle, HoverAdapter, adapter => adapter.provideHover(URI.revive(resource), position, token)); } // --- occurrences registerDocumentHighlightProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentHighlightAdapter(this._documents, provider), extension); this._proxy.$registerDocumentHighlightProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[]> { return this._withAdapter(handle, DocumentHighlightAdapter, adapter => adapter.provideDocumentHighlights(URI.revive(resource), position, token)); } // --- references registerReferenceProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable { const handle = this._addNewAdapter(new ReferenceAdapter(this._documents, provider), extension); this._proxy.$registerReferenceSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<modes.Location[]> { return this._withAdapter(handle, ReferenceAdapter, adapter => adapter.provideReferences(URI.revive(resource), position, context, token)); } // --- quick fix registerCodeActionProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable { const handle = this._addNewAdapter(new CodeActionAdapter(this._documents, this._commands.converter, this._diagnostics, provider, this._logService, extension.identifier), extension); this._proxy.$registerQuickFixSupport(handle, this._transformDocumentSelector(selector), metadata && metadata.providedCodeActionKinds ? metadata.providedCodeActionKinds.map(kind => kind.value) : undefined); return this._createDisposable(handle); } $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<CodeActionDto[]> { return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context, token)); } // --- formatting registerDocumentFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new DocumentFormattingAdapter(this._documents, provider), extension); this._proxy.$registerDocumentFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, DocumentFormattingAdapter, adapter => adapter.provideDocumentFormattingEdits(URI.revive(resource), options, token)); } registerDocumentRangeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable { const handle = this._addNewAdapter(new RangeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerRangeFormattingSupport(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, RangeFormattingAdapter, adapter => adapter.provideDocumentRangeFormattingEdits(URI.revive(resource), range, options, token)); } registerOnTypeFormattingEditProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new OnTypeFormattingAdapter(this._documents, provider), extension); this._proxy.$registerOnTypeFormattingSupport(handle, this._transformDocumentSelector(selector), triggerCharacters); return this._createDisposable(handle); } $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[]> { return this._withAdapter(handle, OnTypeFormattingAdapter, adapter => adapter.provideOnTypeFormattingEdits(URI.revive(resource), position, ch, options, token)); } // --- navigate types registerWorkspaceSymbolProvider(extension: IExtensionDescription, provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { const handle = this._addNewAdapter(new NavigateTypeAdapter(provider), extension); this._proxy.$registerNavigateTypeSupport(handle); return this._createDisposable(handle); } $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<WorkspaceSymbolsDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.provideWorkspaceSymbols(search, token)); } $resolveWorkspaceSymbol(handle: number, symbol: WorkspaceSymbolDto, token: CancellationToken): Promise<WorkspaceSymbolDto> { return this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.resolveWorkspaceSymbol(symbol, token)); } $releaseWorkspaceSymbols(handle: number, id: number): void { this._withAdapter(handle, NavigateTypeAdapter, adapter => adapter.releaseWorkspaceSymbols(id)); } // --- rename registerRenameProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable { const handle = this._addNewAdapter(new RenameAdapter(this._documents, provider), extension); this._proxy.$registerRenameSupport(handle, this._transformDocumentSelector(selector), RenameAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<WorkspaceEditDto> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.provideRenameEdits(URI.revive(resource), position, newName, token)); } $resolveRenameLocation(handle: number, resource: URI, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation> { return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position, token)); } // --- suggestion registerCompletionItemProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, triggerCharacters: string[]): vscode.Disposable { const handle = this._addNewAdapter(new SuggestAdapter(this._documents, this._commands.converter, provider), extension); this._proxy.$registerSuggestSupport(handle, this._transformDocumentSelector(selector), triggerCharacters, SuggestAdapter.supportsResolving(provider)); return this._createDisposable(handle); } $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<SuggestResultDto> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.provideCompletionItems(URI.revive(resource), position, context, token)); } $resolveCompletionItem(handle: number, resource: UriComponents, position: IPosition, suggestion: modes.CompletionItem, token: CancellationToken): Promise<modes.CompletionItem> { return this._withAdapter(handle, SuggestAdapter, adapter => adapter.resolveCompletionItem(URI.revive(resource), position, suggestion, token)); } $releaseCompletionItems(handle: number, id: number): void { this._withAdapter(handle, SuggestAdapter, adapter => adapter.releaseCompletionItems(id)); } // --- parameter hints registerSignatureHelpProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, metadataOrTriggerChars?: string[] | vscode.SignatureHelpProviderMetadata): vscode.Disposable { const metadata: ISerializedSignatureHelpProviderMetadata = Array.isArray(metadataOrTriggerChars) ? { triggerCharacters: metadataOrTriggerChars, retriggerCharacters: [] } : metadataOrTriggerChars; const handle = this._addNewAdapter(new SignatureHelpAdapter(this._documents, provider), extension); this._proxy.$registerSignatureHelpProvider(handle, this._transformDocumentSelector(selector), metadata); return this._createDisposable(handle); } $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<modes.SignatureHelp> { return this._withAdapter(handle, SignatureHelpAdapter, adapter => adapter.provideSignatureHelp(URI.revive(resource), position, context, token)); } // --- links registerDocumentLinkProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable { const handle = this._addNewAdapter(new LinkProviderAdapter(this._documents, this._heapService, provider), extension); this._proxy.$registerDocumentLinkProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.ILink[]> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.provideLinks(URI.revive(resource), token)); } $resolveDocumentLink(handle: number, link: modes.ILink, token: CancellationToken): Promise<modes.ILink> { return this._withAdapter(handle, LinkProviderAdapter, adapter => adapter.resolveLink(link, token)); } registerColorProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable { const handle = this._addNewAdapter(new ColorProviderAdapter(this._documents, provider), extension); this._proxy.$registerDocumentColorProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColors(URI.revive(resource), token)); } $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[]> { return this._withAdapter(handle, ColorProviderAdapter, adapter => adapter.provideColorPresentations(URI.revive(resource), colorInfo, token)); } registerFoldingRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new FoldingProviderAdapter(this._documents, provider), extension); this._proxy.$registerFoldingRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideFoldingRanges(handle: number, resource: UriComponents, context: vscode.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[]> { return this._withAdapter(handle, FoldingProviderAdapter, adapter => adapter.provideFoldingRanges(URI.revive(resource), context, token)); } // --- smart select registerSelectionRangeProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable { const handle = this._addNewAdapter(new SelectionRangeAdapter(this._documents, provider), extension); this._proxy.$registerSelectionRangeProvider(handle, this._transformDocumentSelector(selector)); return this._createDisposable(handle); } $provideSelectionRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.SelectionRange[]> { return this._withAdapter(handle, SelectionRangeAdapter, adapter => adapter.provideSelectionRanges(URI.revive(resource), position, token)); } // --- configuration private static _serializeRegExp(regExp: RegExp): ISerializedRegExp { if (typeof regExp === 'undefined') { return undefined; } if (regExp === null) { return null; } return { pattern: regExp.source, flags: regExpFlags(regExp), }; } private static _serializeIndentationRule(indentationRule: vscode.IndentationRule): ISerializedIndentationRule { if (typeof indentationRule === 'undefined') { return undefined; } if (indentationRule === null) { return null; } return { decreaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.decreaseIndentPattern), increaseIndentPattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.increaseIndentPattern), indentNextLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.indentNextLinePattern), unIndentedLinePattern: ExtHostLanguageFeatures._serializeRegExp(indentationRule.unIndentedLinePattern), }; } private static _serializeOnEnterRule(onEnterRule: vscode.OnEnterRule): ISerializedOnEnterRule { return { beforeText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.beforeText), afterText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.afterText), oneLineAboveText: ExtHostLanguageFeatures._serializeRegExp(onEnterRule.oneLineAboveText), action: onEnterRule.action }; } private static _serializeOnEnterRules(onEnterRules: vscode.OnEnterRule[]): ISerializedOnEnterRule[] { if (typeof onEnterRules === 'undefined') { return undefined; } if (onEnterRules === null) { return null; } return onEnterRules.map(ExtHostLanguageFeatures._serializeOnEnterRule); } setLanguageConfiguration(languageId: string, configuration: vscode.LanguageConfiguration): vscode.Disposable { let { wordPattern } = configuration; // check for a valid word pattern if (wordPattern && regExpLeadsToEndlessLoop(wordPattern)) { throw new Error(`Invalid language configuration: wordPattern '${wordPattern}' is not allowed to match the empty string.`); } // word definition if (wordPattern) { this._documents.setWordDefinitionFor(languageId, wordPattern); } else { this._documents.setWordDefinitionFor(languageId, null); } const handle = this._nextHandle(); const serializedConfiguration: ISerializedLanguageConfiguration = { comments: configuration.comments, brackets: configuration.brackets, wordPattern: ExtHostLanguageFeatures._serializeRegExp(configuration.wordPattern), indentationRules: ExtHostLanguageFeatures._serializeIndentationRule(configuration.indentationRules), onEnterRules: ExtHostLanguageFeatures._serializeOnEnterRules(configuration.onEnterRules), __electricCharacterSupport: configuration.__electricCharacterSupport, __characterPairSupport: configuration.__characterPairSupport, }; this._proxy.$setLanguageConfiguration(handle, languageId, serializedConfiguration); return this._createDisposable(handle); } }
src/vs/workbench/api/node/extHostLanguageFeatures.ts
1
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.9882180094718933, 0.05195422098040581, 0.00015985948266461492, 0.0001765329361660406, 0.2131551057100296 ]
{ "id": 9, "code_window": [ "export namespace DocumentSymbol {\n", "\texport function from(info: vscode.DocumentSymbol): modes.DocumentSymbol {\n", "\t\tconst result: modes.DocumentSymbol = {\n", "\t\t\tname: info.name,\n", "\t\t\tdetail: info.detail,\n", "\t\t\trange: Range.from(info.range),\n", "\t\t\tselectionRange: Range.from(info.selectionRange),\n", "\t\t\tkind: SymbolKind.from(info.kind)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostTypeConverters.ts", "type": "replace", "edit_start_line_idx": 545 }
{ "name": "watch", "version": "1.0.0", "description": "", "author": "Microsoft ", "private": true, "devDependencies": { "gulp-watch": "^4.3.9" } }
build/lib/watch/package.json
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.00017723673954606056, 0.00017491658218204975, 0.0001725964102661237, 0.00017491658218204975, 0.000002320164639968425 ]
{ "id": 9, "code_window": [ "export namespace DocumentSymbol {\n", "\texport function from(info: vscode.DocumentSymbol): modes.DocumentSymbol {\n", "\t\tconst result: modes.DocumentSymbol = {\n", "\t\t\tname: info.name,\n", "\t\t\tdetail: info.detail,\n", "\t\t\trange: Range.from(info.range),\n", "\t\t\tselectionRange: Range.from(info.selectionRange),\n", "\t\t\tkind: SymbolKind.from(info.kind)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostTypeConverters.ts", "type": "replace", "edit_start_line_idx": 545 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-action-bar .action-item .action-label.extension-action { padding: 0 5px; outline-offset: 2px; line-height: initial; } .monaco-action-bar .action-item .action-label.clear-extensions { background: url('clear.svg') center center no-repeat; } .vs-dark .monaco-action-bar .action-item .action-label.clear-extensions, .hc-black .monaco-action-bar .action-item .action-label.clear-extensions { background: url('clear-inverse.svg') center center no-repeat; } .monaco-action-bar .action-item .action-label.extension-action.multiserver.install:after, .monaco-action-bar .action-item .action-label.extension-action.multiserver.update:after, .monaco-action-bar .action-item .action-label.extension-action.extension-editor-dropdown-action.dropdown:after { content: '▼'; padding-left: 2px; font-size: 80%; } .monaco-action-bar .action-item.disabled .action-label.extension-action.ignore, .monaco-action-bar .action-item.disabled .action-label.extension-action.undo-ignore, .monaco-action-bar .action-item.disabled .action-label.extension-action.install:not(.installing), .monaco-action-bar .action-item.disabled .action-label.extension-action.uninstall:not(.uninstalling), .monaco-action-bar .action-item.disabled .action-label.extension-action.update, .monaco-action-bar .action-item.disabled .action-label.extension-action.extension-editor-dropdown-action, .monaco-action-bar .action-item.disabled .action-label.extension-action.reload, .monaco-action-bar .action-item.disabled .action-label.disable-status.hide, .monaco-action-bar .action-item.disabled .action-label.malicious-status.not-malicious { display: none; } .monaco-action-bar .action-item .action-label.disable-status, .monaco-action-bar .action-item .action-label.malicious-status { border-radius: 4px; color: inherit; background-color: transparent; opacity: 0.9; font-style: italic; padding: 0 5px; line-height: initial; } .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.disable-status, .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.malicious-status { font-weight: normal; } .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.disable-status:hover, .extension-editor>.header>.details>.actions>.monaco-action-bar .action-item .action-label.malicious-status:hover { opacity: 0.9; } .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage.hide { display: none; } .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage { height: 18px; width: 10px; border: none; background: url('manage.svg') center center no-repeat; outline-offset: 0px; margin-top: 0.15em } .hc-black .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage, .vs-dark .extensions-viewlet>.extensions .extension>.details>.footer>.monaco-action-bar .action-item .action-label.extension-action.manage { background: url('manage-inverse.svg') center center no-repeat; } .extension-editor > .header.recommended > .details > .recommendation > .monaco-action-bar .actions-container { justify-content: flex-start; }
src/vs/workbench/parts/extensions/electron-browser/media/extensionActions.css
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0001748429931467399, 0.00017241848399862647, 0.0001685106399236247, 0.0001731735246721655, 0.0000020475388282648055 ]
{ "id": 9, "code_window": [ "export namespace DocumentSymbol {\n", "\texport function from(info: vscode.DocumentSymbol): modes.DocumentSymbol {\n", "\t\tconst result: modes.DocumentSymbol = {\n", "\t\t\tname: info.name,\n", "\t\t\tdetail: info.detail,\n", "\t\t\trange: Range.from(info.range),\n", "\t\t\tselectionRange: Range.from(info.selectionRange),\n", "\t\t\tkind: SymbolKind.from(info.kind)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tname: info.name || '!!MISSING: name!!',\n" ], "file_path": "src/vs/workbench/api/node/extHostTypeConverters.ts", "type": "replace", "edit_start_line_idx": 545 }
#if B4G_DEBUG_CHECK fprintf(stderr,"num_candidate_ret=%d:", num_candidate); for(int i=0;i<num_candidate;++i) fprintf(stderr,"%d,",user_candidate[i]); fprintf(stderr,";"); #endif void main(O obj) { LOG_INFO("not hilighted as string"); LOG_INFO(obj << ", even worse; " << obj.x << " check this out."); // everything from this point on is interpeted as a string literal... O x; std::unique_ptr<O> o(new O); // sadness. sprintf(options, "STYLE=Keramik;TITLE=%s;THEME=%s", ...); } int main2() { printf(";"); // the rest of asm("movw $0x38, %ax; ltr %ax"); fn("{};"); // the rest of }
extensions/cpp/test/colorize-fixtures/test.cc
0
https://github.com/microsoft/vscode/commit/f9dac5925447293678b81e817fa077a5bc1b9d3c
[ 0.0001780696475179866, 0.00017491677135694772, 0.00017169526836369187, 0.00017498542729299515, 0.000002602782160465722 ]
{ "id": 0, "code_window": [ " return (\n", " <div style={{ marginLeft: '100px', position: 'relative', display: 'inline-block' }}>\n", " <ButtonSelect\n", " {...args}\n", " onChange={(value) => {\n", " action('onChange fired')(value);\n", " updateArgs({ value });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " variant=\"canvas\"\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.internal.story.tsx", "type": "add", "edit_start_line_idx": 29 }
import { css } from '@emotion/css'; import { useButton } from '@react-aria/button'; import { FocusScope } from '@react-aria/focus'; import { useMenuTrigger } from '@react-aria/menu'; import { useMenuTriggerState } from '@react-stately/menu'; import React, { HTMLAttributes } from 'react'; import { GrafanaTheme2, SelectableValue } from '@grafana/data'; import { useStyles2 } from '../../themes/ThemeContext'; import { ButtonGroup } from '../Button'; import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper'; import { Menu } from '../Menu/Menu'; import { MenuItem } from '../Menu/MenuItem'; import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton'; import { PopoverContent } from '../Tooltip'; export interface Props<T> extends HTMLAttributes<HTMLButtonElement> { className?: string; options: Array<SelectableValue<T>>; value?: SelectableValue<T>; onChange: (item: SelectableValue<T>) => void; /** @deprecated use tooltip instead, tooltipContent is not being processed in ToolbarButton*/ tooltipContent?: PopoverContent; narrow?: boolean; variant?: ToolbarButtonVariant; tooltip?: string; } /** * @internal * A temporary component until we have a proper dropdown component */ const ButtonSelectComponent = <T,>(props: Props<T>) => { const { className, options, value, onChange, narrow, variant, ...restProps } = props; const styles = useStyles2(getStyles); const state = useMenuTriggerState({}); const ref = React.useRef(null); const { menuTriggerProps, menuProps } = useMenuTrigger({}, state, ref); const { buttonProps } = useButton(menuTriggerProps, ref); const onChangeInternal = (item: SelectableValue<T>) => { onChange(item); state.close(); }; return ( <ButtonGroup className={styles.wrapper}> <ToolbarButton className={className} isOpen={state.isOpen} narrow={narrow} variant={variant} ref={ref} {...buttonProps} {...restProps} > {value?.label || (value?.value != null ? String(value?.value) : null)} </ToolbarButton> {state.isOpen && ( <div className={styles.menuWrapper}> <ClickOutsideWrapper onClick={state.close} parent={document} includeButtonPress={false}> <FocusScope contain autoFocus restoreFocus> {/* tabIndex=-1 is needed here to support highlighting text within the menu when using FocusScope see https://github.com/adobe/react-spectrum/issues/1604#issuecomment-781574668 */} <Menu tabIndex={-1} onClose={state.close} {...menuProps} autoFocus={!!menuProps.autoFocus}> {options.map((item) => ( <MenuItem key={`${item.value}`} label={item.label ?? String(item.value)} onClick={() => onChangeInternal(item)} active={item.value === value?.value} ariaChecked={item.value === value?.value} ariaLabel={item.ariaLabel || item.label} role="menuitemradio" /> ))} </Menu> </FocusScope> </ClickOutsideWrapper> </div> )} </ButtonGroup> ); }; ButtonSelectComponent.displayName = 'ButtonSelect'; // needed to properly forward the generic type through React.memo // see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37087#issuecomment-656596623 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions export const ButtonSelect = React.memo(ButtonSelectComponent) as typeof ButtonSelectComponent; const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css({ position: 'relative', display: 'inline-flex', }), menuWrapper: css({ position: 'absolute', zIndex: theme.zIndex.dropdown, top: theme.spacing(4), right: 0, }), }; };
packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx
1
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.9654793739318848, 0.16153453290462494, 0.00016764730389695615, 0.0004334945697337389, 0.35914167761802673 ]
{ "id": 0, "code_window": [ " return (\n", " <div style={{ marginLeft: '100px', position: 'relative', display: 'inline-block' }}>\n", " <ButtonSelect\n", " {...args}\n", " onChange={(value) => {\n", " action('onChange fired')(value);\n", " updateArgs({ value });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " variant=\"canvas\"\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.internal.story.tsx", "type": "add", "edit_start_line_idx": 29 }
import { CorsWorker as Worker } from 'app/core/utils/CorsWorker'; // CorsWorker is needed as a workaround for CORS issue caused // by static assets served from an url different from origin export const createWorker = () => new Worker(new URL('./routeGroupsMatcher.worker.ts', import.meta.url));
public/app/features/alerting/unified/createRouteGroupsMatcherWorker.ts
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017369262059219182, 0.00017369262059219182, 0.00017369262059219182, 0.00017369262059219182, 0 ]
{ "id": 0, "code_window": [ " return (\n", " <div style={{ marginLeft: '100px', position: 'relative', display: 'inline-block' }}>\n", " <ButtonSelect\n", " {...args}\n", " onChange={(value) => {\n", " action('onChange fired')(value);\n", " updateArgs({ value });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " variant=\"canvas\"\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.internal.story.tsx", "type": "add", "edit_start_line_idx": 29 }
package resources import ( "encoding/json" "fmt" "github.com/grafana/grafana/pkg/tsdb/cloudwatch/constants" ) func parseDimensionFilter(dimensionFilter string) ([]*Dimension, error) { dimensionFilters := map[string]any{} dimensionFilterJson := []byte(dimensionFilter) if len(dimensionFilterJson) > 0 { err := json.Unmarshal(dimensionFilterJson, &dimensionFilters) if err != nil { return nil, fmt.Errorf("error unmarshaling dimensionFilters: %v", err) } } dimensions := []*Dimension{} addDimension := func(key string, value string) { d := &Dimension{ Name: key, } // if value is not specified or a wildcard is used, simply don't use the value field if value != "" && value != "*" { d.Value = value } dimensions = append(dimensions, d) } for k, v := range dimensionFilters { // due to legacy, value can be a string, a string slice or nil if vv, ok := v.(string); ok { addDimension(k, vv) } else if vv, ok := v.([]any); ok { for _, v := range vv { addDimension(k, v.(string)) } } else if v == nil { addDimension(k, "") } } return dimensions, nil } func isCustomNamespace(namespace string) bool { if _, ok := constants.NamespaceMetricsMap[namespace]; ok { return false } return true }
pkg/tsdb/cloudwatch/models/resources/utils.go
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017698612646199763, 0.00017225007468368858, 0.00016799518198240548, 0.00017234691767953336, 0.0000031094289170141565 ]
{ "id": 0, "code_window": [ " return (\n", " <div style={{ marginLeft: '100px', position: 'relative', display: 'inline-block' }}>\n", " <ButtonSelect\n", " {...args}\n", " onChange={(value) => {\n", " action('onChange fired')(value);\n", " updateArgs({ value });\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " variant=\"canvas\"\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.internal.story.tsx", "type": "add", "edit_start_line_idx": 29 }
import { OrgRole, OrgUser } from 'app/types'; import { UsersFetchResult, initialState } from '../state/reducers'; export const getFetchUsersMock = (amount: number): UsersFetchResult => { const users = getMockUsers(amount); return { orgUsers: users as OrgUser[], perPage: initialState.perPage, page: initialState.page, totalCount: initialState.totalPages, }; }; export const getMockUsers = (amount: number): OrgUser[] => { const users = []; for (let i = 0; i <= amount; i++) { users.push({ avatarUrl: 'url/to/avatar', email: `user-${i}@test.com`, name: `user-${i} test`, lastSeenAt: '2018-10-01', lastSeenAtAge: '', login: `user-${i}`, orgId: 1, role: 'Admin', userId: i, isDisabled: false, authLabels: [], }); } return users as OrgUser[]; }; export const getMockUser = () => { return { avatarUrl: 'url/to/avatar', email: `[email protected]`, name: 'user test', lastSeenAt: '2018-10-01', lastSeenAtAge: '', login: `user`, orgId: 1, role: 'Admin' as OrgRole, userId: 2, } as OrgUser; }; export const getMockInvitees = (amount: number) => { const invitees = []; for (let i = 0; i <= amount; i++) { invitees.push({ code: `asdfasdfsadf-${i}`, createdOn: '2018-10-02', email: `invitee-${i}@test.com`, emailSent: true, emailSentOn: '2018-10-02', id: i, invitedByEmail: '[email protected]', invitedByLogin: 'admin', invitedByName: 'admin', name: `invitee-${i}`, orgId: 1, role: 'viewer', status: 'not accepted', url: `localhost/invite/${i}`, }); } return invitees; };
public/app/features/users/__mocks__/userMocks.ts
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017827605188358575, 0.00017537959502078593, 0.0001714264799375087, 0.00017603962623979896, 0.0000025403983272553887 ]
{ "id": 1, "code_window": [ "import { GrafanaTheme2, SelectableValue } from '@grafana/data';\n", "\n", "import { useStyles2 } from '../../themes/ThemeContext';\n", "import { ButtonGroup } from '../Button';\n", "import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';\n", "import { Menu } from '../Menu/Menu';\n", "import { MenuItem } from '../Menu/MenuItem';\n", "import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton';\n", "import { PopoverContent } from '../Tooltip';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 10 }
import { css } from '@emotion/css'; import { useButton } from '@react-aria/button'; import { FocusScope } from '@react-aria/focus'; import { useMenuTrigger } from '@react-aria/menu'; import { useMenuTriggerState } from '@react-stately/menu'; import React, { HTMLAttributes } from 'react'; import { GrafanaTheme2, SelectableValue } from '@grafana/data'; import { useStyles2 } from '../../themes/ThemeContext'; import { ButtonGroup } from '../Button'; import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper'; import { Menu } from '../Menu/Menu'; import { MenuItem } from '../Menu/MenuItem'; import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton'; import { PopoverContent } from '../Tooltip'; export interface Props<T> extends HTMLAttributes<HTMLButtonElement> { className?: string; options: Array<SelectableValue<T>>; value?: SelectableValue<T>; onChange: (item: SelectableValue<T>) => void; /** @deprecated use tooltip instead, tooltipContent is not being processed in ToolbarButton*/ tooltipContent?: PopoverContent; narrow?: boolean; variant?: ToolbarButtonVariant; tooltip?: string; } /** * @internal * A temporary component until we have a proper dropdown component */ const ButtonSelectComponent = <T,>(props: Props<T>) => { const { className, options, value, onChange, narrow, variant, ...restProps } = props; const styles = useStyles2(getStyles); const state = useMenuTriggerState({}); const ref = React.useRef(null); const { menuTriggerProps, menuProps } = useMenuTrigger({}, state, ref); const { buttonProps } = useButton(menuTriggerProps, ref); const onChangeInternal = (item: SelectableValue<T>) => { onChange(item); state.close(); }; return ( <ButtonGroup className={styles.wrapper}> <ToolbarButton className={className} isOpen={state.isOpen} narrow={narrow} variant={variant} ref={ref} {...buttonProps} {...restProps} > {value?.label || (value?.value != null ? String(value?.value) : null)} </ToolbarButton> {state.isOpen && ( <div className={styles.menuWrapper}> <ClickOutsideWrapper onClick={state.close} parent={document} includeButtonPress={false}> <FocusScope contain autoFocus restoreFocus> {/* tabIndex=-1 is needed here to support highlighting text within the menu when using FocusScope see https://github.com/adobe/react-spectrum/issues/1604#issuecomment-781574668 */} <Menu tabIndex={-1} onClose={state.close} {...menuProps} autoFocus={!!menuProps.autoFocus}> {options.map((item) => ( <MenuItem key={`${item.value}`} label={item.label ?? String(item.value)} onClick={() => onChangeInternal(item)} active={item.value === value?.value} ariaChecked={item.value === value?.value} ariaLabel={item.ariaLabel || item.label} role="menuitemradio" /> ))} </Menu> </FocusScope> </ClickOutsideWrapper> </div> )} </ButtonGroup> ); }; ButtonSelectComponent.displayName = 'ButtonSelect'; // needed to properly forward the generic type through React.memo // see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37087#issuecomment-656596623 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions export const ButtonSelect = React.memo(ButtonSelectComponent) as typeof ButtonSelectComponent; const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css({ position: 'relative', display: 'inline-flex', }), menuWrapper: css({ position: 'absolute', zIndex: theme.zIndex.dropdown, top: theme.spacing(4), right: 0, }), }; };
packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx
1
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.3116209805011749, 0.02693268470466137, 0.0001687093754298985, 0.0005276098963804543, 0.08584664016962051 ]
{ "id": 1, "code_window": [ "import { GrafanaTheme2, SelectableValue } from '@grafana/data';\n", "\n", "import { useStyles2 } from '../../themes/ThemeContext';\n", "import { ButtonGroup } from '../Button';\n", "import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';\n", "import { Menu } from '../Menu/Menu';\n", "import { MenuItem } from '../Menu/MenuItem';\n", "import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton';\n", "import { PopoverContent } from '../Tooltip';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 10 }
--- keywords: - grafana - dashboard - dashboard folders - create - build - design labels: products: - cloud - enterprise - oss menuTitle: Build dashboards title: Build dashboards weight: 2 --- # Build dashboards This section includes the following topics: {{< section >}} ## Dynamic dashboards You can create more interactive and dynamic dashboards by adding and using [variables][]. Instead of hard-coding things like server, application, and sensor names in your metric queries, you can use variables in their place. Read more about variables [here][variables]. {{% docs/reference %}} [variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables" [variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/variables" {{% /docs/reference %}}
docs/sources/dashboards/build-dashboards/_index.md
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017576015670783818, 0.00016740606224630028, 0.00016347997006960213, 0.0001651920611038804, 0.000004986314252164448 ]
{ "id": 1, "code_window": [ "import { GrafanaTheme2, SelectableValue } from '@grafana/data';\n", "\n", "import { useStyles2 } from '../../themes/ThemeContext';\n", "import { ButtonGroup } from '../Button';\n", "import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';\n", "import { Menu } from '../Menu/Menu';\n", "import { MenuItem } from '../Menu/MenuItem';\n", "import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton';\n", "import { PopoverContent } from '../Tooltip';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 10 }
package api import ( "net/http" "strconv" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" . "github.com/grafana/grafana/pkg/services/publicdashboards/models" "github.com/grafana/grafana/pkg/services/publicdashboards/validation" "github.com/grafana/grafana/pkg/web" ) // swagger:route GET /public/dashboards/{accessToken} dashboard_public viewPublicDashboard // // Get public dashboard for view // // Responses: // 200: viewPublicDashboardResponse // 400: badRequestPublicError // 401: unauthorisedPublicError // 403: forbiddenPublicError // 404: notFoundPublicError // 500: internalServerPublicError func (api *Api) ViewPublicDashboard(c *contextmodel.ReqContext) response.Response { accessToken := web.Params(c.Req)[":accessToken"] if !validation.IsValidAccessToken(accessToken) { return response.Err(ErrInvalidAccessToken.Errorf("ViewPublicDashboard: invalid access token")) } dto, err := api.PublicDashboardService.GetPublicDashboardForView(c.Req.Context(), accessToken) if err != nil { return response.Err(err) } return response.JSON(http.StatusOK, dto) } // swagger:route POST /public/dashboards/{accessToken}/panels/{panelId}/query dashboard_public queryPublicDashboard // // Get results for a given panel on a public dashboard // // Responses: // 200: queryPublicDashboardResponse // 400: badRequestPublicError // 401: unauthorisedPublicError // 404: panelNotFoundPublicError // 404: notFoundPublicError // 403: forbiddenPublicError // 500: internalServerPublicError func (api *Api) QueryPublicDashboard(c *contextmodel.ReqContext) response.Response { accessToken := web.Params(c.Req)[":accessToken"] if !validation.IsValidAccessToken(accessToken) { return response.Err(ErrInvalidAccessToken.Errorf("QueryPublicDashboard: invalid access token")) } panelId, err := strconv.ParseInt(web.Params(c.Req)[":panelId"], 10, 64) if err != nil { return response.Err(ErrInvalidPanelId.Errorf("QueryPublicDashboard: error parsing panelId %v", err)) } reqDTO := PublicDashboardQueryDTO{} if err = web.Bind(c.Req, &reqDTO); err != nil { return response.Err(ErrBadRequest.Errorf("QueryPublicDashboard: error parsing request: %v", err)) } resp, err := api.PublicDashboardService.GetQueryDataResponse(c.Req.Context(), c.SkipDSCache, reqDTO, panelId, accessToken) if err != nil { return response.Err(err) } return toJsonStreamingResponse(api.Features, resp) } // swagger:route GET /public/dashboards/{accessToken}/annotations dashboard_public getPublicAnnotations // // Get annotations for a public dashboard // // Responses: // 200: getPublicAnnotationsResponse // 400: badRequestPublicError // 404: notFoundPublicError // 401: unauthorisedPublicError // 403: forbiddenPublicError // 500: internalServerPublicError func (api *Api) GetPublicAnnotations(c *contextmodel.ReqContext) response.Response { accessToken := web.Params(c.Req)[":accessToken"] if !validation.IsValidAccessToken(accessToken) { return response.Err(ErrInvalidAccessToken.Errorf("GetPublicAnnotations: invalid access token")) } reqDTO := AnnotationsQueryDTO{ From: c.QueryInt64("from"), To: c.QueryInt64("to"), } annotations, err := api.PublicDashboardService.FindAnnotations(c.Req.Context(), reqDTO, accessToken) if err != nil { return response.Err(err) } return response.JSON(http.StatusOK, annotations) } // swagger:response viewPublicDashboardResponse type ViewPublicDashboardResponse struct { // in: body Body dtos.DashboardFullWithMeta `json:"body"` } // swagger:parameters viewPublicDashboard type ViewPublicDashboardParams struct { // in: path AccessToken string `json:"accessToken"` } // swagger:response queryPublicDashboardResponse type QueryPublicDashboardResponse struct { // in: body Body backend.QueryDataResponse `json:"body"` } // swagger:parameters queryPublicDashboard type QueryPublicDashboardParams struct { // in: path AccessToken string `json:"accessToken"` // in: path PanelId int64 `json:"panelId"` } // swagger:response getPublicAnnotationsResponse type GetPublicAnnotationsResponse struct { // in: body Body []AnnotationEvent `json:"body"` } // swagger:parameters getPublicAnnotations type GetPublicAnnotationsParams struct { // in: path AccessToken string `json:"accessToken"` }
pkg/services/publicdashboards/api/query.go
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.0001735297410050407, 0.00017057126387953758, 0.00016413271077908576, 0.00017180433496832848, 0.0000025818833364610327 ]
{ "id": 1, "code_window": [ "import { GrafanaTheme2, SelectableValue } from '@grafana/data';\n", "\n", "import { useStyles2 } from '../../themes/ThemeContext';\n", "import { ButtonGroup } from '../Button';\n", "import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper';\n", "import { Menu } from '../Menu/Menu';\n", "import { MenuItem } from '../Menu/MenuItem';\n", "import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton';\n", "import { PopoverContent } from '../Tooltip';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 10 }
package database import ( "context" "strconv" "strings" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/services/accesscontrol" ) func ProvideService(sql db.DB) *AccessControlStore { return &AccessControlStore{sql} } type AccessControlStore struct { sql db.DB } func (s *AccessControlStore) GetUserPermissions(ctx context.Context, query accesscontrol.GetUserPermissionsQuery) ([]accesscontrol.Permission, error) { result := make([]accesscontrol.Permission, 0) err := s.sql.WithDbSession(ctx, func(sess *db.Session) error { if query.UserID == 0 && len(query.TeamIDs) == 0 && len(query.Roles) == 0 { // no permission to fetch return nil } filter, params := accesscontrol.UserRolesFilter(query.OrgID, query.UserID, query.TeamIDs, query.Roles) q := ` SELECT permission.action, permission.scope FROM permission INNER JOIN role ON role.id = permission.role_id ` + filter if len(query.RolePrefixes) > 0 { q += " WHERE ( " + strings.Repeat("role.name LIKE ? OR ", len(query.RolePrefixes)) q = q[:len(q)-4] + " )" // remove last " OR " for i := range query.RolePrefixes { params = append(params, query.RolePrefixes[i]+"%") } } if err := sess.SQL(q, params...).Find(&result); err != nil { return err } return nil }) return result, err } // SearchUsersPermissions returns the list of user permissions indexed by UserID func (s *AccessControlStore) SearchUsersPermissions(ctx context.Context, orgID int64, options accesscontrol.SearchOptions) (map[int64][]accesscontrol.Permission, error) { type UserRBACPermission struct { UserID int64 `xorm:"user_id"` Action string `xorm:"action"` Scope string `xorm:"scope"` } dbPerms := make([]UserRBACPermission, 0) if err := s.sql.WithDbSession(ctx, func(sess *db.Session) error { // Find permissions q := ` SELECT user_id, action, scope FROM ( SELECT ur.user_id, ur.org_id, p.action, p.scope FROM permission AS p INNER JOIN user_role AS ur on ur.role_id = p.role_id UNION ALL SELECT tm.user_id, tr.org_id, p.action, p.scope FROM permission AS p INNER JOIN team_role AS tr ON tr.role_id = p.role_id INNER JOIN team_member AS tm ON tm.team_id = tr.team_id UNION ALL SELECT ou.user_id, ou.org_id, p.action, p.scope FROM permission AS p INNER JOIN builtin_role AS br ON br.role_id = p.role_id INNER JOIN org_user AS ou ON ou.role = br.role UNION ALL SELECT sa.user_id, br.org_id, p.action, p.scope FROM permission AS p INNER JOIN builtin_role AS br ON br.role_id = p.role_id INNER JOIN ( SELECT u.id AS user_id FROM ` + s.sql.GetDialect().Quote("user") + ` AS u WHERE u.is_admin ) AS sa ON 1 = 1 WHERE br.role = ? ) AS up WHERE (org_id = ? OR org_id = ?) ` params := []any{accesscontrol.RoleGrafanaAdmin, accesscontrol.GlobalOrgID, orgID} if options.ActionPrefix != "" { q += ` AND action LIKE ?` params = append(params, options.ActionPrefix+"%") } if options.Action != "" { q += ` AND action = ?` params = append(params, options.Action) } if options.Scope != "" { q += ` AND scope = ?` params = append(params, options.Scope) } if options.UserID != 0 { q += ` AND user_id = ?` params = append(params, options.UserID) } return sess.SQL(q, params...). Find(&dbPerms) }); err != nil { return nil, err } mapped := map[int64][]accesscontrol.Permission{} for i := range dbPerms { mapped[dbPerms[i].UserID] = append(mapped[dbPerms[i].UserID], accesscontrol.Permission{Action: dbPerms[i].Action, Scope: dbPerms[i].Scope}) } return mapped, nil } // GetUsersBasicRoles returns the list of user basic roles (Admin, Editor, Viewer, Grafana Admin) indexed by UserID func (s *AccessControlStore) GetUsersBasicRoles(ctx context.Context, userFilter []int64, orgID int64) (map[int64][]string, error) { type UserOrgRole struct { UserID int64 `xorm:"id"` OrgRole string `xorm:"role"` IsAdmin bool `xorm:"is_admin"` } dbRoles := make([]UserOrgRole, 0) if err := s.sql.WithDbSession(ctx, func(sess *db.Session) error { // Find roles q := ` SELECT u.id, ou.role, u.is_admin FROM ` + s.sql.GetDialect().Quote("user") + ` AS u LEFT JOIN org_user AS ou ON u.id = ou.user_id WHERE (u.is_admin OR ou.org_id = ?) ` params := []any{orgID} if len(userFilter) > 0 { q += "AND u.id IN (?" + strings.Repeat(",?", len(userFilter)-1) + ")" for _, u := range userFilter { params = append(params, u) } } return sess.SQL(q, params...).Find(&dbRoles) }); err != nil { return nil, err } roles := map[int64][]string{} for i := range dbRoles { if dbRoles[i].OrgRole != "" { roles[dbRoles[i].UserID] = []string{dbRoles[i].OrgRole} } if dbRoles[i].IsAdmin { roles[dbRoles[i].UserID] = append(roles[dbRoles[i].UserID], accesscontrol.RoleGrafanaAdmin) } } return roles, nil } func (s *AccessControlStore) DeleteUserPermissions(ctx context.Context, orgID, userID int64) error { err := s.sql.WithDbSession(ctx, func(sess *db.Session) error { roleDeleteQuery := "DELETE FROM user_role WHERE user_id = ?" roleDeleteParams := []any{roleDeleteQuery, userID} if orgID != accesscontrol.GlobalOrgID { roleDeleteQuery += " AND org_id = ?" roleDeleteParams = []any{roleDeleteQuery, userID, orgID} } // Delete user role assignments if _, err := sess.Exec(roleDeleteParams...); err != nil { return err } // only delete scopes to user if all permissions is removed (i.e. user is removed) if orgID == accesscontrol.GlobalOrgID { // Delete permissions that are scoped to user if _, err := sess.Exec("DELETE FROM permission WHERE scope = ?", accesscontrol.Scope("users", "id", strconv.FormatInt(userID, 10))); err != nil { return err } } roleQuery := "SELECT id FROM role WHERE name = ?" roleParams := []any{accesscontrol.ManagedUserRoleName(userID)} if orgID != accesscontrol.GlobalOrgID { roleQuery += " AND org_id = ?" roleParams = []any{accesscontrol.ManagedUserRoleName(userID), orgID} } var roleIDs []int64 if err := sess.SQL(roleQuery, roleParams...).Find(&roleIDs); err != nil { return err } if len(roleIDs) == 0 { return nil } permissionDeleteQuery := "DELETE FROM permission WHERE role_id IN(? " + strings.Repeat(",?", len(roleIDs)-1) + ")" permissionDeleteParams := make([]any, 0, len(roleIDs)+1) permissionDeleteParams = append(permissionDeleteParams, permissionDeleteQuery) for _, id := range roleIDs { permissionDeleteParams = append(permissionDeleteParams, id) } // Delete managed user permissions if _, err := sess.Exec(permissionDeleteParams...); err != nil { return err } managedRoleDeleteQuery := "DELETE FROM role WHERE id IN(? " + strings.Repeat(",?", len(roleIDs)-1) + ")" managedRoleDeleteParams := []any{managedRoleDeleteQuery} for _, id := range roleIDs { managedRoleDeleteParams = append(managedRoleDeleteParams, id) } // Delete managed user roles if _, err := sess.Exec(managedRoleDeleteParams...); err != nil { return err } return nil }) return err }
pkg/services/accesscontrol/database/database.go
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.0001959067303687334, 0.00017347732500638813, 0.00016689162293914706, 0.00017323027714155614, 0.000005438330390461488 ]
{ "id": 2, "code_window": [ " };\n", "\n", " return (\n", " <ButtonGroup className={styles.wrapper}>\n", " <ToolbarButton\n", " className={className}\n", " isOpen={state.isOpen}\n", " narrow={narrow}\n", " variant={variant}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.wrapper}>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 48 }
import { css } from '@emotion/css'; import { useButton } from '@react-aria/button'; import { FocusScope } from '@react-aria/focus'; import { useMenuTrigger } from '@react-aria/menu'; import { useMenuTriggerState } from '@react-stately/menu'; import React, { HTMLAttributes } from 'react'; import { GrafanaTheme2, SelectableValue } from '@grafana/data'; import { useStyles2 } from '../../themes/ThemeContext'; import { ButtonGroup } from '../Button'; import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper'; import { Menu } from '../Menu/Menu'; import { MenuItem } from '../Menu/MenuItem'; import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton'; import { PopoverContent } from '../Tooltip'; export interface Props<T> extends HTMLAttributes<HTMLButtonElement> { className?: string; options: Array<SelectableValue<T>>; value?: SelectableValue<T>; onChange: (item: SelectableValue<T>) => void; /** @deprecated use tooltip instead, tooltipContent is not being processed in ToolbarButton*/ tooltipContent?: PopoverContent; narrow?: boolean; variant?: ToolbarButtonVariant; tooltip?: string; } /** * @internal * A temporary component until we have a proper dropdown component */ const ButtonSelectComponent = <T,>(props: Props<T>) => { const { className, options, value, onChange, narrow, variant, ...restProps } = props; const styles = useStyles2(getStyles); const state = useMenuTriggerState({}); const ref = React.useRef(null); const { menuTriggerProps, menuProps } = useMenuTrigger({}, state, ref); const { buttonProps } = useButton(menuTriggerProps, ref); const onChangeInternal = (item: SelectableValue<T>) => { onChange(item); state.close(); }; return ( <ButtonGroup className={styles.wrapper}> <ToolbarButton className={className} isOpen={state.isOpen} narrow={narrow} variant={variant} ref={ref} {...buttonProps} {...restProps} > {value?.label || (value?.value != null ? String(value?.value) : null)} </ToolbarButton> {state.isOpen && ( <div className={styles.menuWrapper}> <ClickOutsideWrapper onClick={state.close} parent={document} includeButtonPress={false}> <FocusScope contain autoFocus restoreFocus> {/* tabIndex=-1 is needed here to support highlighting text within the menu when using FocusScope see https://github.com/adobe/react-spectrum/issues/1604#issuecomment-781574668 */} <Menu tabIndex={-1} onClose={state.close} {...menuProps} autoFocus={!!menuProps.autoFocus}> {options.map((item) => ( <MenuItem key={`${item.value}`} label={item.label ?? String(item.value)} onClick={() => onChangeInternal(item)} active={item.value === value?.value} ariaChecked={item.value === value?.value} ariaLabel={item.ariaLabel || item.label} role="menuitemradio" /> ))} </Menu> </FocusScope> </ClickOutsideWrapper> </div> )} </ButtonGroup> ); }; ButtonSelectComponent.displayName = 'ButtonSelect'; // needed to properly forward the generic type through React.memo // see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37087#issuecomment-656596623 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions export const ButtonSelect = React.memo(ButtonSelectComponent) as typeof ButtonSelectComponent; const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css({ position: 'relative', display: 'inline-flex', }), menuWrapper: css({ position: 'absolute', zIndex: theme.zIndex.dropdown, top: theme.spacing(4), right: 0, }), }; };
packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx
1
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.48356392979621887, 0.07621965557336807, 0.00016976181359495968, 0.0002900308172684163, 0.16956451535224915 ]
{ "id": 2, "code_window": [ " };\n", "\n", " return (\n", " <ButtonGroup className={styles.wrapper}>\n", " <ToolbarButton\n", " className={className}\n", " isOpen={state.isOpen}\n", " narrow={narrow}\n", " variant={variant}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.wrapper}>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 48 }
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { of } from 'rxjs'; import { createFetchResponse } from 'test/helpers/createFetchResponse'; import { DataQueryRequest, DataSourceInstanceSettings, dateTime, PluginMetaInfo, PluginType } from '@grafana/data'; import { backendSrv } from 'app/core/services/backend_srv'; import { JaegerDatasource, JaegerJsonData } from '../datasource'; import { testResponse } from '../testResponse'; import { JaegerQuery } from '../types'; import SearchForm from './SearchForm'; jest.mock('@grafana/runtime', () => ({ ...jest.requireActual('@grafana/runtime'), getTemplateSrv: () => ({ replace: jest.fn(), containsTemplate: (val: string): boolean => { return val.includes('$'); }, }), })); describe('SearchForm', () => { it('should call the `onChange` function on click of the Input', async () => { const promise = Promise.resolve(); const handleOnChange = jest.fn(() => promise); const query = { ...defaultQuery, refId: '121314', }; const ds = { async metadataRequest(url) { if (url === '/api/services') { return Promise.resolve(['jaeger-query', 'service2', 'service3']); } return undefined; }, } as JaegerDatasource; setupFetchMock({ data: [testResponse] }); render(<SearchForm datasource={ds} query={query} onChange={handleOnChange} />); const asyncServiceSelect = await waitFor(() => screen.getByRole('combobox', { name: 'select-service-name' })); expect(asyncServiceSelect).toBeInTheDocument(); await userEvent.click(asyncServiceSelect); const jaegerService = await screen.findByText('jaeger-query'); expect(jaegerService).toBeInTheDocument(); }); it('should be able to select operation name if query.service exists', async () => { const promise = Promise.resolve(); const handleOnChange = jest.fn(() => promise); const query2 = { ...defaultQuery, refId: '121314', service: 'jaeger-query', }; setupFetchMock({ data: [testResponse] }); render(<SearchForm datasource={{} as JaegerDatasource} query={query2} onChange={handleOnChange} />); const asyncOperationSelect2 = await waitFor(() => screen.getByRole('combobox', { name: 'select-operation-name' })); expect(asyncOperationSelect2).toBeInTheDocument(); }); }); describe('SearchForm', () => { let user: ReturnType<typeof userEvent.setup>; let query: JaegerQuery; let ds: JaegerDatasource; beforeEach(() => { jest.useFakeTimers(); // Need to use delay: null here to work with fakeTimers // see https://github.com/testing-library/user-event/issues/833 user = userEvent.setup({ delay: null }); query = { ...defaultQuery, refId: '121314', service: 'jaeger-query', }; ds = new JaegerDatasource(defaultSettings); setupFetchMock({ data: [testResponse] }); jest.spyOn(ds, 'metadataRequest').mockImplementation(() => { return new Promise((resolve) => { setTimeout(() => { resolve(['jaeger-query']); }, 3000); }); }); }); afterEach(() => { jest.useRealTimers(); }); it('should show loader if there is a delay fetching options', async () => { const handleOnChange = jest.fn(); render(<SearchForm datasource={ds} query={query} onChange={handleOnChange} />); const asyncServiceSelect = screen.getByRole('combobox', { name: 'select-service-name' }); await user.click(asyncServiceSelect); expect(screen.getByText('Loading options...')).toBeInTheDocument(); jest.advanceTimersByTime(3000); await waitFor(() => expect(screen.queryByText('Loading options...')).not.toBeInTheDocument()); }); it('should filter the span dropdown when user types a search value', async () => { render(<SearchForm datasource={ds} query={query} onChange={() => {}} />); const asyncServiceSelect = screen.getByRole('combobox', { name: 'select-service-name' }); expect(asyncServiceSelect).toBeInTheDocument(); await user.click(asyncServiceSelect); jest.advanceTimersByTime(3000); await user.type(asyncServiceSelect, 'j'); let option = await screen.findByText('jaeger-query'); expect(option).toBeDefined(); await user.type(asyncServiceSelect, 'c'); option = await screen.findByText('Hit enter to add'); expect(option).toBeDefined(); }); it('should add variable to select menu options', async () => { query = { ...defaultQuery, refId: '121314', service: '$service', operation: '$operation', }; render(<SearchForm datasource={ds} query={query} onChange={() => {}} />); const asyncServiceSelect = screen.getByRole('combobox', { name: 'select-service-name' }); expect(asyncServiceSelect).toBeInTheDocument(); await user.click(asyncServiceSelect); jest.advanceTimersByTime(3000); await user.type(asyncServiceSelect, '$'); const serviceOption = await screen.findByText('$service'); expect(serviceOption).toBeDefined(); const asyncOperationSelect = screen.getByRole('combobox', { name: 'select-operation-name' }); expect(asyncOperationSelect).toBeInTheDocument(); await user.click(asyncOperationSelect); jest.advanceTimersByTime(3000); await user.type(asyncOperationSelect, '$'); const operationOption = await screen.findByText('$operation'); expect(operationOption).toBeDefined(); }); }); function setupFetchMock(response: unknown, mock?: ReturnType<typeof backendSrv.fetch>) { const defaultMock = () => mock ?? of(createFetchResponse(response)); const fetchMock = jest.spyOn(backendSrv, 'fetch'); fetchMock.mockImplementation(defaultMock); return fetchMock; } const defaultSettings: DataSourceInstanceSettings<JaegerJsonData> = { id: 0, uid: '0', type: 'tracing', name: 'jaeger', url: 'http://grafana.com', access: 'proxy', meta: { id: 'jaeger', name: 'jaeger', type: PluginType.datasource, info: {} as PluginMetaInfo, module: '', baseUrl: '', }, jsonData: { nodeGraph: { enabled: true, }, }, readOnly: false, }; const defaultQuery: DataQueryRequest<JaegerQuery> = { requestId: '1', interval: '0', intervalMs: 10, panelId: 0, scopedVars: {}, range: { from: dateTime().subtract(1, 'h'), to: dateTime(), raw: { from: '1h', to: 'now' }, }, timezone: 'browser', app: 'explore', startTime: 0, targets: [ { query: '12345', refId: '1', }, ], };
public/app/plugins/datasource/jaeger/components/SearchForm.test.tsx
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.0001774826378095895, 0.00017468348960392177, 0.00016788150242064148, 0.00017498686793260276, 0.000001972439349628985 ]
{ "id": 2, "code_window": [ " };\n", "\n", " return (\n", " <ButtonGroup className={styles.wrapper}>\n", " <ToolbarButton\n", " className={className}\n", " isOpen={state.isOpen}\n", " narrow={narrow}\n", " variant={variant}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.wrapper}>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 48 }
let templates = (require as any).context('../', true, /\.html$/); templates.keys().forEach((key: string) => { templates(key); });
public/app/angular/partials.ts
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.0001617372181499377, 0.0001617372181499377, 0.0001617372181499377, 0.0001617372181499377, 0 ]
{ "id": 2, "code_window": [ " };\n", "\n", " return (\n", " <ButtonGroup className={styles.wrapper}>\n", " <ToolbarButton\n", " className={className}\n", " isOpen={state.isOpen}\n", " narrow={narrow}\n", " variant={variant}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div className={styles.wrapper}>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 48 }
--- labels: products: - enterprise - oss title: Select home dashboard list --- 1. Click to select an option in the **Timezone** list. **Default** is either the browser local timezone or the timezone selected at a higher level. 1. Click **Save**.
docs/sources/shared/preferences/select-timezone-list.md
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017730012768879533, 0.00017336165183223784, 0.00016942319052759558, 0.00017336165183223784, 0.000003938468580599874 ]
{ "id": 3, "code_window": [ " </FocusScope>\n", " </ClickOutsideWrapper>\n", " </div>\n", " )}\n", " </ButtonGroup>\n", " );\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " </div>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 85 }
import { css } from '@emotion/css'; import { useButton } from '@react-aria/button'; import { FocusScope } from '@react-aria/focus'; import { useMenuTrigger } from '@react-aria/menu'; import { useMenuTriggerState } from '@react-stately/menu'; import React, { HTMLAttributes } from 'react'; import { GrafanaTheme2, SelectableValue } from '@grafana/data'; import { useStyles2 } from '../../themes/ThemeContext'; import { ButtonGroup } from '../Button'; import { ClickOutsideWrapper } from '../ClickOutsideWrapper/ClickOutsideWrapper'; import { Menu } from '../Menu/Menu'; import { MenuItem } from '../Menu/MenuItem'; import { ToolbarButton, ToolbarButtonVariant } from '../ToolbarButton'; import { PopoverContent } from '../Tooltip'; export interface Props<T> extends HTMLAttributes<HTMLButtonElement> { className?: string; options: Array<SelectableValue<T>>; value?: SelectableValue<T>; onChange: (item: SelectableValue<T>) => void; /** @deprecated use tooltip instead, tooltipContent is not being processed in ToolbarButton*/ tooltipContent?: PopoverContent; narrow?: boolean; variant?: ToolbarButtonVariant; tooltip?: string; } /** * @internal * A temporary component until we have a proper dropdown component */ const ButtonSelectComponent = <T,>(props: Props<T>) => { const { className, options, value, onChange, narrow, variant, ...restProps } = props; const styles = useStyles2(getStyles); const state = useMenuTriggerState({}); const ref = React.useRef(null); const { menuTriggerProps, menuProps } = useMenuTrigger({}, state, ref); const { buttonProps } = useButton(menuTriggerProps, ref); const onChangeInternal = (item: SelectableValue<T>) => { onChange(item); state.close(); }; return ( <ButtonGroup className={styles.wrapper}> <ToolbarButton className={className} isOpen={state.isOpen} narrow={narrow} variant={variant} ref={ref} {...buttonProps} {...restProps} > {value?.label || (value?.value != null ? String(value?.value) : null)} </ToolbarButton> {state.isOpen && ( <div className={styles.menuWrapper}> <ClickOutsideWrapper onClick={state.close} parent={document} includeButtonPress={false}> <FocusScope contain autoFocus restoreFocus> {/* tabIndex=-1 is needed here to support highlighting text within the menu when using FocusScope see https://github.com/adobe/react-spectrum/issues/1604#issuecomment-781574668 */} <Menu tabIndex={-1} onClose={state.close} {...menuProps} autoFocus={!!menuProps.autoFocus}> {options.map((item) => ( <MenuItem key={`${item.value}`} label={item.label ?? String(item.value)} onClick={() => onChangeInternal(item)} active={item.value === value?.value} ariaChecked={item.value === value?.value} ariaLabel={item.ariaLabel || item.label} role="menuitemradio" /> ))} </Menu> </FocusScope> </ClickOutsideWrapper> </div> )} </ButtonGroup> ); }; ButtonSelectComponent.displayName = 'ButtonSelect'; // needed to properly forward the generic type through React.memo // see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37087#issuecomment-656596623 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions export const ButtonSelect = React.memo(ButtonSelectComponent) as typeof ButtonSelectComponent; const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css({ position: 'relative', display: 'inline-flex', }), menuWrapper: css({ position: 'absolute', zIndex: theme.zIndex.dropdown, top: theme.spacing(4), right: 0, }), }; };
packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx
1
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.5963703989982605, 0.04992138221859932, 0.00016425419016741216, 0.00017452772590331733, 0.16476061940193176 ]
{ "id": 3, "code_window": [ " </FocusScope>\n", " </ClickOutsideWrapper>\n", " </div>\n", " )}\n", " </ButtonGroup>\n", " );\n", "};\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " </div>\n" ], "file_path": "packages/grafana-ui/src/components/Dropdown/ButtonSelect.tsx", "type": "replace", "edit_start_line_idx": 85 }
package loganalytics import ( "fmt" "github.com/grafana/grafana-azure-sdk-go/azsettings" "github.com/grafana/grafana-plugin-sdk-go/data" ) func AddCustomDataLink(frame data.Frame, dataLink data.DataLink) data.Frame { for i := range frame.Fields { if frame.Fields[i].Config == nil { frame.Fields[i].Config = &data.FieldConfig{} } frame.Fields[i].Config.Links = append(frame.Fields[i].Config.Links, dataLink) } return frame } func AddConfigLinks(frame data.Frame, dl string, title *string) data.Frame { linkTitle := "View in Azure Portal" if title != nil { linkTitle = *title } deepLink := data.DataLink{ Title: linkTitle, TargetBlank: true, URL: dl, } frame = AddCustomDataLink(frame, deepLink) return frame } func GetAzurePortalUrl(azureCloud string) (string, error) { switch azureCloud { case azsettings.AzurePublic: return "https://portal.azure.com", nil case azsettings.AzureChina: return "https://portal.azure.cn", nil case azsettings.AzureUSGovernment: return "https://portal.azure.us", nil default: return "", fmt.Errorf("the cloud is not supported") } }
pkg/tsdb/azuremonitor/loganalytics/utils.go
0
https://github.com/grafana/grafana/commit/a46ff31c4f515dc7984fce3c60e6cd750bf32072
[ 0.00017908753943629563, 0.0001735205005388707, 0.00016565971600357443, 0.00017476531502325088, 0.000004761198397318367 ]