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": 2, "code_window": [ "\n", " $(\"input[type='radio']\").checkboxradio({ mini: true });\n", " $(\"input[type='radio']\").checkboxradio({ theme: \"a\" });\n", " $(\"input[type='radio']\").checkboxradio('enable');\n", " $(\"input[type='radio']:first\").attr(\"checked\", true).checkboxradio(\"refresh\");\n", " $(\"input[type='radio']\").checkboxradio({\n", " create: function (event, ui) { }\n", " });\n", "\n", " $('select').selectmenu();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $(\"input[type='radio']:first\").prop(\"checked\", true).checkboxradio(\"refresh\");\n" ], "file_path": "jquerymobile/jquerymobile-tests.ts", "type": "replace", "edit_start_line_idx": 218 }
/// <reference path="../jquery/jquery.d.ts"/> /// <reference path="jquery.watermark.d.ts"/> $('#inputId').watermark('Required information'); $('#inputId').watermark('Required information', { className: 'myClassName' }); $('#inputId').watermark('Search', { useNative: false }); $.watermark.options.className = 'myClass'; $.watermark.options.useNative = false; var myFunction; $.watermark.options.useNative = myFunction; $.watermark.options.hideBeforeUnload = false; $.watermark.options = { className: 'myClass', useNative: false, hideBeforeUnload: false }; $.watermark.options.hideBeforeUnload = true; $.watermark.show('input.optional'); $.watermark.hide('#myInput'); $.watermark.showAll(); $.watermark.hideAll();
jquery.watermark/jquery.watermark-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.00017241991008631885, 0.00016837236762512475, 0.00016461953055113554, 0.00016807769134175032, 0.0000031913016300677555 ]
{ "id": 2, "code_window": [ "\n", " $(\"input[type='radio']\").checkboxradio({ mini: true });\n", " $(\"input[type='radio']\").checkboxradio({ theme: \"a\" });\n", " $(\"input[type='radio']\").checkboxradio('enable');\n", " $(\"input[type='radio']:first\").attr(\"checked\", true).checkboxradio(\"refresh\");\n", " $(\"input[type='radio']\").checkboxradio({\n", " create: function (event, ui) { }\n", " });\n", "\n", " $('select').selectmenu();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $(\"input[type='radio']:first\").prop(\"checked\", true).checkboxradio(\"refresh\");\n" ], "file_path": "jquerymobile/jquerymobile-tests.ts", "type": "replace", "edit_start_line_idx": 218 }
// Type definitions for Impress.js 0.5 // Project: https://github.com/bartaz/impress.js // Definitions by: Boris Yankov <https://github.com/borisyankov/> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Impress { init(): void; getStep(step: any): any; goto(element: any, duration?: number): any; prev(): any; next(): any; } declare function impress(): Impress;
impress/impress.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/3b581e015208e939a8fddf14c9ad430d96abf491
[ 0.00017413689056411386, 0.00017410327563993633, 0.0001740696607157588, 0.00017410327563993633, 3.361492417752743e-8 ]
{ "id": 0, "code_window": [ " /**\n", " * @private\n", " */\n", " ngOnDestroy() {\n", " this._form.deregister(this);\n", " this._group.remove(this);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " if (this._group) {\n", " this._group.remove(this);\n", " }\n" ], "file_path": "ionic/components/radio/radio-button.ts", "type": "replace", "edit_start_line_idx": 157 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0003337716334499419, 0.00019419263117015362, 0.00016486096137668937, 0.00017823604866862297, 0.000045023782149655744 ]
{ "id": 0, "code_window": [ " /**\n", " * @private\n", " */\n", " ngOnDestroy() {\n", " this._form.deregister(this);\n", " this._group.remove(this);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " if (this._group) {\n", " this._group.remove(this);\n", " }\n" ], "file_path": "ionic/components/radio/radio-button.ts", "type": "replace", "edit_start_line_idx": 157 }
import {Component, Renderer, ElementRef, HostListener, ViewEncapsulation} from 'angular2/core'; import {Animation} from '../../animations/animation'; import {Transition, TransitionOptions} from '../../transitions/transition'; import {Config} from '../../config/config'; import {isPresent, isUndefined, isDefined} from '../../util/util'; import {NavParams} from '../nav/nav-params'; import {ViewController} from '../nav/view-controller'; /** * @name Loading * @description * An overlay that can be used to indicate activity while blocking user * interaction. The loading indicator appears on top of the app's content, * and can be dismissed by the app to resume user interaction with * the app. It includes an optional backdrop, which can be disabled * by setting `showBackdrop: false` upon creation. * * ### Creating * You can pass all of the loading options in the first argument of * the create method: `Loading.create(opts)`. The spinner name should be * passed in the `spinner` property, and any optional HTML can be passed * in the `content` property. If you do not pass a value to `spinner` * the loading indicator will use the spinner specified by the mode. To * set the spinner name across the app, set the value of `loadingSpinner` * in your app's config. To hide the spinner, set `loadingSpinner: 'hide'` * in the app's config or pass `spinner: 'hide'` in the loading * options. See the [create](#create) method below for all available options. * * ### Dismissing * The loading indicator can be dismissed automatically after a specific * amount of time by passing the number of milliseconds to display it in * the `duration` of the loading options. By default the loading indicator * will show even during page changes, but this can be disabled by setting * `dismissOnPageChange` to `true`. To dismiss the loading indicator after * creation, call the `dismiss()` method on the Loading instance. The * `onDismiss` function can be called to perform an action after the loading * indicator is dismissed. * * >Note that after the component is dismissed, it will not be usable anymore * and another one must be created. This can be avoided by wrapping the * creation and presentation of the component in a reusable function as shown * in the `usage` section below. * * ### Limitations * The element is styled to appear on top of other content by setting its * `z-index` property. You must ensure no element has a stacking context with * a higher `z-index` than this element. * * @usage * ```ts * constructor(nav: NavController) { * this.nav = nav; * } * * presentLoadingDefault() { * let loading = Loading.create({ * content: 'Please wait...' * }); * * this.nav.present(loading); * * setTimeout(() => { * loading.dismiss(); * }, 5000); * } * * presentLoadingCustom() { * let loading = Loading.create({ * spinner: 'hide', * content: ` * <div class="custom-spinner-container"> * <div class="custom-spinner-box"></div> * </div>`, * duration: 5000 * }); * * loading.onDismiss(() => { * console.log('Dismissed loading'); * }); * * this.nav.present(loading); * } * * presentLoadingText() { * let loading = Loading.create({ * spinner: 'hide', * content: 'Loading Please Wait...' * }); * * this.nav.present(loading); * * setTimeout(() => { * this.nav.push(Page2); * }, 1000); * * setTimeout(() => { * loading.dismiss(); * }, 5000); * } * ``` * * @demo /docs/v2/demos/loading/ * @see {@link /docs/v2/api/components/spinner/Spinner Spinner API Docs} */ export class Loading extends ViewController { constructor(opts: LoadingOptions = {}) { opts.showBackdrop = isPresent(opts.showBackdrop) ? !!opts.showBackdrop : true; opts.dismissOnPageChange = isPresent(opts.dismissOnPageChange) ? !!opts.dismissOnPageChange : false; super(LoadingCmp, opts); this.viewType = 'loading'; this.isOverlay = true; this.usePortal = true; // by default, loading indicators should not fire lifecycle events of other views // for example, when an loading indicators enters, the current active view should // not fire its lifecycle events because it's not conceptually leaving this.fireOtherLifecycles = false; } /** * @private */ getTransitionName(direction: string) { let key = (direction === 'back' ? 'loadingLeave' : 'loadingEnter'); return this._nav && this._nav.config.get(key); } /** * Create a loading indicator with the following options * * | Option | Type | Description | * |-----------------------|------------|------------------------------------------------------------------------------------------------------------------| * | spinner |`string` | The name of the SVG spinner for the loading indicator. | * | content |`string` | The html content for the loading indicator. | * | cssClass |`string` | An additional class for custom styles. | * | showBackdrop |`boolean` | Whether to show the backdrop. Default true. | * | dismissOnPageChange |`boolean` | Whether to dismiss the indicator when navigating to a new page. Default false. | * | duration |`number` | How many milliseconds to wait before hiding the indicator. By default, it will show until `dismiss()` is called. | * * * @param {object} opts Loading options */ static create(opts: LoadingOptions = {}) { return new Loading(opts); } } /** * @private */ @Component({ selector: 'ion-loading', template: '<div disable-activated class="backdrop" [class.hide-backdrop]="!d.showBackdrop" role="presentation"></div>' + '<div class="loading-wrapper">' + '<div *ngIf="showSpinner" class="loading-spinner">' + '<ion-spinner [name]="d.spinner"></ion-spinner>' + '</div>' + '<div *ngIf="d.content" [innerHTML]="d.content" class="loading-content"></div>' + '</div>', host: { 'role': 'dialog' }, encapsulation: ViewEncapsulation.None, }) class LoadingCmp { private d: any; private id: number; private created: number; private showSpinner: boolean; constructor( private _viewCtrl: ViewController, private _config: Config, private _elementRef: ElementRef, params: NavParams, renderer: Renderer ) { this.d = params.data; this.created = Date.now(); if (this.d.cssClass) { renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true); } this.id = (++loadingIds); } ngOnInit() { // If no spinner was passed in loading options we need to fall back // to the loadingSpinner in the app's config, then the mode spinner if (isUndefined(this.d.spinner)) { this.d.spinner = this._config.get('loadingSpinner', this._config.get('spinner', 'ios')); } // If the user passed hide to the spinner we don't want to show it this.showSpinner = isDefined(this.d.spinner) && this.d.spinner !== 'hide'; } onPageDidEnter() { let activeElement: any = document.activeElement; if (document.activeElement) { activeElement.blur(); } // If there is a duration, dismiss after that amount of time this.d.duration ? setTimeout(() => this.dismiss('backdrop'), this.d.duration) : null; } dismiss(role): Promise<any> { return this._viewCtrl.dismiss(null, role); } isEnabled() { let tm = this._config.getNumber('overlayCreatedDiff', 750); return (this.created + tm < Date.now()); } } export interface LoadingOptions { spinner?: string; content?: string; cssClass?: string; showBackdrop?: boolean; dismissOnPageChange?: boolean; delay?: number; duration?: number; } /** * Animations for loading */ class LoadingPopIn extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = enteringView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '0.01', '1').fromTo('scale', '1.1', '1'); backdrop.fromTo('opacity', '0.01', '0.3'); this .easing('ease-in-out') .duration(200) .add(backdrop) .add(wrapper); } } Transition.register('loading-pop-in', LoadingPopIn); class LoadingPopOut extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = leavingView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '1', '0').fromTo('scale', '1', '0.9'); backdrop.fromTo('opacity', '0.3', '0'); this .easing('ease-in-out') .duration(200) .add(backdrop) .add(wrapper); } } Transition.register('loading-pop-out', LoadingPopOut); class LoadingMdPopIn extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = enteringView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '0.01', '1').fromTo('scale', '1.1', '1'); backdrop.fromTo('opacity', '0.01', '0.50'); this .easing('ease-in-out') .duration(200) .add(backdrop) .add(wrapper); } } Transition.register('loading-md-pop-in', LoadingMdPopIn); class LoadingMdPopOut extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = leavingView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '1', '0').fromTo('scale', '1', '0.9'); backdrop.fromTo('opacity', '0.50', '0'); this .easing('ease-in-out') .duration(200) .add(backdrop) .add(wrapper); } } Transition.register('loading-md-pop-out', LoadingMdPopOut); class LoadingWpPopIn extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = enteringView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '0.01', '1').fromTo('scale', '1.3', '1'); backdrop.fromTo('opacity', '0.01', '0.16'); this .easing('cubic-bezier(0,0 0.05,1)') .duration(200) .add(backdrop) .add(wrapper); } } Transition.register('loading-wp-pop-in', LoadingWpPopIn); class LoadingWpPopOut extends Transition { constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) { super(opts); let ele = leavingView.pageRef().nativeElement; let backdrop = new Animation(ele.querySelector('.backdrop')); let wrapper = new Animation(ele.querySelector('.loading-wrapper')); wrapper.fromTo('opacity', '1', '0').fromTo('scale', '1', '1.3'); backdrop.fromTo('opacity', '0.16', '0'); this .easing('ease-out') .duration(150) .add(backdrop) .add(wrapper); } } Transition.register('loading-wp-pop-out', LoadingWpPopOut); let loadingIds = -1;
ionic/components/loading/loading.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0006825159071013331, 0.000196832770598121, 0.00016128431889228523, 0.00017174717504531145, 0.00008945209992816672 ]
{ "id": 0, "code_window": [ " /**\n", " * @private\n", " */\n", " ngOnDestroy() {\n", " this._form.deregister(this);\n", " this._group.remove(this);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " if (this._group) {\n", " this._group.remove(this);\n", " }\n" ], "file_path": "ionic/components/radio/radio-button.ts", "type": "replace", "edit_start_line_idx": 157 }
<ion-toolbar> <ion-title>Icons</ion-title> </ion-toolbar> <ion-content> <ion-list> <ion-item> <ion-icon name="home" item-left></ion-icon> <code> name="home" </code> </ion-item> <ion-item> <ion-icon [name]="homeIcon" item-left></ion-icon> <code> [name]="homeIcon" </code> </ion-item> <ion-item> <ion-icon name="home" isActive="true" item-left></ion-icon> <code> name="home" isActive="true" </code> </ion-item> <ion-item> <ion-icon name="home" [isActive]="isActive" item-left></ion-icon> <code> name="home" [isActive]="isActive" </code> </ion-item> <ion-item> <ion-icon name="ios-home" item-left></ion-icon> <code> name="ios-home" </code> </ion-item> <ion-item> <ion-icon name="ios-home-outline" item-left></ion-icon> <code> name="ios-home-outline" </code> </ion-item> <ion-item> <ion-icon name="md-home" item-left></ion-icon> <code> name="md-home" </code> </ion-item> <ion-item> <ion-icon name="logo-twitter" item-left></ion-icon> <code> name="logo-twitter" </code> </ion-item> <ion-item> <ion-icon ios="logo-apple" md="logo-android" item-left></ion-icon> <code> ios="logo-apple" md="logo-android" </code> </ion-item> <ion-item detail-push> <code> ion-item w/ [detail-push] attr. text text text text text text </code> </ion-item> </ion-list> <p> <button (click)="updateIcon()"> <ion-icon [name]="btnIcon"></ion-icon> Update icon </button> </p> </ion-content> <style> /*to ensure ng css encapsulation doesn't mess with icon attributes*/ code { font-size: 0.8em; } </style>
ionic/components/icon/test/basic/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001740391307976097, 0.0001685684110270813, 0.00016592514293733984, 0.00016756718105170876, 0.0000028230174393684138 ]
{ "id": 0, "code_window": [ " /**\n", " * @private\n", " */\n", " ngOnDestroy() {\n", " this._form.deregister(this);\n", " this._group.remove(this);\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " if (this._group) {\n", " this._group.remove(this);\n", " }\n" ], "file_path": "ionic/components/radio/radio-button.ts", "type": "replace", "edit_start_line_idx": 157 }
$font-path: "../fonts"; $roboto-font-path: "../fonts"; // http://ionicframework.com/docs/v2/theming/ // App Shared Variables // -------------------------------------------------- // To customize the look and feel of this app, you can override // the Sass variables found in Ionic's source scss files. Setting // variables before Ionic's Sass will use these variables rather than // Ionic's default Sass variable values. App Shared Sass imports belong // in the app.core.scss file and not this file. Sass variables specific // to the mode belong in either the app.ios.scss or app.md.scss files. // App Shared Color Variables // -------------------------------------------------- // It's highly recommended to change the default colors // to match your app's branding. Ionic uses a Sass map of // colors so you can add, rename and remove colors as needed. // The "primary" color is the only required color in the map. // Both iOS and MD colors can be further customized if colors // are different per mode. $colors: ( primary: #387ef5, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, vibrant: rebeccapurple, bright: #FFC125 ); @import "../ionic/ionic.md";
demos/output.md.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017704891797620803, 0.000172173953615129, 0.00016765001055318862, 0.0001719984575174749, 0.0000035705681966646807 ]
{ "id": 1, "code_window": [ " });\n", "\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 88 }
import {Component, Optional, Input, Output, HostListener, EventEmitter, ViewEncapsulation} from 'angular2/core'; import {Form} from '../../util/form'; import {isTrueProperty, isPresent, isBlank, isCheckedProperty} from '../../util/util'; import {Item} from '../item/item'; import {ListHeader} from '../list/list'; import {RadioGroup} from './radio-group'; /** * @description * A radio button with a unique value. Note that all `<ion-radio>` * components must be wrapped within a `<ion-list radio-group>`, * and there must be at least two `<ion-radio>` components within * the radio group. * * See the [Angular 2 Docs](https://angular.io/docs/ts/latest/guide/forms.html) for * more info on forms and input. * * @usage * ```html * * <ion-item> * <ion-label>Radio Label</ion-label> * <ion-radio value="radio-value"></ion-radio> * </ion-item> * * ``` * @demo /docs/v2/demos/radio/ * @see {@link /docs/v2/components#radio Radio Component Docs} */ @Component({ selector: 'ion-radio', template: '<div class="radio-icon" [class.radio-checked]="_checked">' + '<div class="radio-inner"></div>' + '</div>' + '<button role="radio" ' + 'type="button" ' + 'category="item-cover" ' + '[id]="id" ' + '[attr.aria-checked]="_checked" ' + '[attr.aria-labelledby]="_labelId" ' + '[attr.aria-disabled]="_disabled" ' + 'class="item-cover">' + '</button>', host: { '[class.radio-disabled]': '_disabled' }, encapsulation: ViewEncapsulation.None, }) export class RadioButton { private _checked: boolean = false; private _disabled: boolean = false; private _labelId: string; private _value: any = null; /** * @private */ id: string; /** * @output {any} expression to be evaluated when selected */ @Output() select: EventEmitter<any> = new EventEmitter(); constructor( private _form: Form, @Optional() private _item: Item, @Optional() private _group: RadioGroup ) { _form.register(this); if (_group) { // register with the radiogroup this.id = 'rb-' + _group.add(this); } if (_item) { // register the input inside of the item // reset to the item's id instead of the radiogroup id this.id = 'rb-' + _item.registerInput('radio'); this._labelId = 'lbl-' + _item.id; this._item.setCssClass('item-radio', true); } } /** * @private */ @Input() get value(): any { // if the value is not defined then use it's unique id return isBlank(this._value) ? this.id : this._value; } set value(val: any) { this._value = val; } /** * @private */ @Input() get checked(): boolean { return this._checked; } set checked(isChecked: boolean) { this._checked = isTrueProperty(isChecked); if (this._item) { this._item.setCssClass('item-radio-checked', this._checked); } } /** * @private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(val: boolean) { this._disabled = isTrueProperty(val); this._item && this._item.setCssClass('item-radio-disabled', this._disabled); } /** * @private */ @HostListener('click', ['$event']) private _click(ev) { console.debug('radio, select', this.id); ev.preventDefault(); ev.stopPropagation(); this.checked = true; this.select.emit(this.value); } /** * @private */ ngOnInit() { if (this._group && isPresent(this._group.value)) { this.checked = isCheckedProperty(this._group.value, this.value); } } /** * @private */ ngOnDestroy() { this._form.deregister(this); this._group.remove(this); } }
ionic/components/radio/radio-button.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00022770090436097234, 0.00017904312699101865, 0.00016651632904540747, 0.0001696732797427103, 0.000019750827050302178 ]
{ "id": 1, "code_window": [ " });\n", "\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 88 }
<ion-toolbar> <ion-title>Icon</ion-title> </ion-toolbar> <ion-content text-center class="icon-demo"> <ion-row> <ion-col><ion-icon name="ionic" primary></ion-icon></ion-col> <ion-col><ion-icon name="logo-angular"></ion-icon></ion-col> <ion-col><ion-icon name="heart" danger></ion-icon></ion-col> <ion-col><ion-icon name="ionitron" primary></ion-icon></ion-col> <ion-col><ion-icon name="happy" vibrant></ion-icon></ion-col> <ion-col><ion-icon name="people"></ion-icon></ion-col> <ion-col><ion-icon name="person"></ion-icon></ion-col> <ion-col><ion-icon name="contact"></ion-icon></ion-col> <ion-col><ion-icon name="apps"></ion-icon></ion-col> <ion-col><ion-icon name="lock"></ion-icon></ion-col> <ion-col><ion-icon name="key" bright></ion-icon></ion-col> <ion-col><ion-icon name="unlock"></ion-icon></ion-col> <ion-col><ion-icon name="map" secondary></ion-icon></ion-col> <ion-col><ion-icon name="navigate"></ion-icon></ion-col> <ion-col><ion-icon name="pin"></ion-icon></ion-col> <ion-col><ion-icon name="locate"></ion-icon></ion-col> <ion-col><ion-icon name="mic"></ion-icon></ion-col> <ion-col><ion-icon name="musical-notes" vibrant></ion-icon></ion-col> <ion-col><ion-icon name="volume-up"></ion-icon></ion-col> <ion-col><ion-icon name="microphone"></ion-icon></ion-col> <ion-col><ion-icon name="cafe" bright></ion-icon></ion-col> <ion-col><ion-icon name="calculator"></ion-icon></ion-col> <ion-col><ion-icon name="bus"></ion-icon></ion-col> <ion-col><ion-icon name="wine" danger></ion-icon></ion-col> <ion-col><ion-icon name="camera"></ion-icon></ion-col> <ion-col><ion-icon name="image" secondary></ion-icon></ion-col> <ion-col><ion-icon name="star" bright></ion-icon></ion-col> <ion-col><ion-icon name="pin"></ion-icon></ion-col> <ion-col><ion-icon name="arrow-dropup-circle" vibrant></ion-icon></ion-col> <ion-col><ion-icon name="arrow-back"></ion-icon></ion-col> <ion-col><ion-icon name="arrow-dropdown"></ion-icon></ion-col> <ion-col><ion-icon name="arrow-forward"></ion-icon></ion-col> <ion-col><ion-icon name="cloud"></ion-icon></ion-col> <ion-col><ion-icon name="sunny" bright></ion-icon></ion-col> <ion-col><ion-icon name="umbrella"></ion-icon></ion-col> <ion-col><ion-icon name="rainy" primary></ion-icon></ion-col> </ion-row> </ion-content> <style> .icon-demo ion-icon { font-size: 50px; } .icon-demo ion-row { height: 100%; flex-wrap: wrap; } .icon-demo ion-col { flex: 0 0 25%; max-width: 25%; text-align: center; padding: 10px 5px; } </style>
demos/icon/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018530699890106916, 0.00017665127234067768, 0.00016843642515596002, 0.0001755091652739793, 0.000006092870080465218 ]
{ "id": 1, "code_window": [ " });\n", "\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 88 }
@import "../../globals.core"; // Alerts // -------------------------------------------------- $alert-min-width: 250px !default; $alert-max-height: 90% !default; $alert-button-line-height: 20px !default; $alert-button-font-size: 14px !default; ion-alert { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: $z-index-overlay; display: flex; align-items: center; justify-content: center; input { width: 100%; } } .alert-wrapper { z-index: $z-index-overlay-wrapper; display: flex; flex-direction: column; min-width: $alert-min-width; max-height: $alert-max-height; opacity: 0; } .alert-title { margin: 0; padding: 0; } .alert-sub-title { margin: 5px 0 0; padding: 0; font-weight: normal; } .alert-message { overflow: auto; } .alert-input { @include placeholder(); padding: 10px 0; border: 0; background: inherit; } .alert-button-group { display: flex; flex-direction: row; &.vertical { flex-direction: column; flex-wrap: nowrap; } } .alert-button { z-index: 0; display: block; margin: 0; font-size: $alert-button-font-size; line-height: $alert-button-line-height; } .alert-tappable { margin: 0; padding: 0; width: 100%; font-size: inherit; line-height: initial; text-align: left; background: transparent; -webkit-appearance: none; }
ionic/components/alert/alert.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018229011038783938, 0.00017096829833462834, 0.00016509834676980972, 0.0001715483085718006, 0.00000425176995122456 ]
{ "id": 1, "code_window": [ " });\n", "\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 88 }
@import "../../globals.wp"; // Windows App // -------------------------------------------------- ion-content { color: $text-wp-color; } p { color: $paragraph-wp-color; } a { color: $link-wp-color; } hr { background-color: rgba(0, 0, 0, .08); } @each $color-name, $color-base, $color-contrast in get-colors($colors-wp) { h1, h2, h3, h4, h5, h6, p, span, a:not([button]), small, b, i, strong, em, sub, sup, ion-icon { &[#{$color-name}] { color: $color-base; } } }
ionic/components/app/app.wp.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001873040309874341, 0.0001751001545926556, 0.00016704095469322056, 0.0001732453820295632, 0.0000073615328801679425 ]
{ "id": 2, "code_window": [ "\n", " let rg: RadioGroup;\n", " let form: Form;\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ " describe('RadioButton', () => {\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 89 }
import {Component, Optional, Input, Output, HostListener, EventEmitter, ViewEncapsulation} from 'angular2/core'; import {Form} from '../../util/form'; import {isTrueProperty, isPresent, isBlank, isCheckedProperty} from '../../util/util'; import {Item} from '../item/item'; import {ListHeader} from '../list/list'; import {RadioGroup} from './radio-group'; /** * @description * A radio button with a unique value. Note that all `<ion-radio>` * components must be wrapped within a `<ion-list radio-group>`, * and there must be at least two `<ion-radio>` components within * the radio group. * * See the [Angular 2 Docs](https://angular.io/docs/ts/latest/guide/forms.html) for * more info on forms and input. * * @usage * ```html * * <ion-item> * <ion-label>Radio Label</ion-label> * <ion-radio value="radio-value"></ion-radio> * </ion-item> * * ``` * @demo /docs/v2/demos/radio/ * @see {@link /docs/v2/components#radio Radio Component Docs} */ @Component({ selector: 'ion-radio', template: '<div class="radio-icon" [class.radio-checked]="_checked">' + '<div class="radio-inner"></div>' + '</div>' + '<button role="radio" ' + 'type="button" ' + 'category="item-cover" ' + '[id]="id" ' + '[attr.aria-checked]="_checked" ' + '[attr.aria-labelledby]="_labelId" ' + '[attr.aria-disabled]="_disabled" ' + 'class="item-cover">' + '</button>', host: { '[class.radio-disabled]': '_disabled' }, encapsulation: ViewEncapsulation.None, }) export class RadioButton { private _checked: boolean = false; private _disabled: boolean = false; private _labelId: string; private _value: any = null; /** * @private */ id: string; /** * @output {any} expression to be evaluated when selected */ @Output() select: EventEmitter<any> = new EventEmitter(); constructor( private _form: Form, @Optional() private _item: Item, @Optional() private _group: RadioGroup ) { _form.register(this); if (_group) { // register with the radiogroup this.id = 'rb-' + _group.add(this); } if (_item) { // register the input inside of the item // reset to the item's id instead of the radiogroup id this.id = 'rb-' + _item.registerInput('radio'); this._labelId = 'lbl-' + _item.id; this._item.setCssClass('item-radio', true); } } /** * @private */ @Input() get value(): any { // if the value is not defined then use it's unique id return isBlank(this._value) ? this.id : this._value; } set value(val: any) { this._value = val; } /** * @private */ @Input() get checked(): boolean { return this._checked; } set checked(isChecked: boolean) { this._checked = isTrueProperty(isChecked); if (this._item) { this._item.setCssClass('item-radio-checked', this._checked); } } /** * @private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(val: boolean) { this._disabled = isTrueProperty(val); this._item && this._item.setCssClass('item-radio-disabled', this._disabled); } /** * @private */ @HostListener('click', ['$event']) private _click(ev) { console.debug('radio, select', this.id); ev.preventDefault(); ev.stopPropagation(); this.checked = true; this.select.emit(this.value); } /** * @private */ ngOnInit() { if (this._group && isPresent(this._group.value)) { this.checked = isCheckedProperty(this._group.value, this.value); } } /** * @private */ ngOnDestroy() { this._form.deregister(this); this._group.remove(this); } }
ionic/components/radio/radio-button.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.9547880291938782, 0.10609441250562668, 0.00016664435679558665, 0.00018218722834717482, 0.2838100492954254 ]
{ "id": 2, "code_window": [ "\n", " let rg: RadioGroup;\n", " let form: Form;\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ " describe('RadioButton', () => {\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 89 }
<!-- Generated template for the <%= jsClassName %> component. See https://angular.io/docs/ts/latest/api/core/ComponentMetadata-class.html for more info on Angular 2 Components. --> <div> {{text}} </div>
tooling/generators/component/component.tmpl.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001685202878434211, 0.0001685202878434211, 0.0001685202878434211, 0.0001685202878434211, 0 ]
{ "id": 2, "code_window": [ "\n", " let rg: RadioGroup;\n", " let form: Form;\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ " describe('RadioButton', () => {\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 89 }
import {App, IonicApp, Page, Events} from 'ionic-angular'; @Page({templateUrl: 'login.html'}) class Login { constructor(events: Events) { this.events = events; this.user = { name: "Administrator", username: "admin" }; } login() { this.events.publish('user:login'); } } @Page({templateUrl: 'logout.html'}) class Logout { constructor(events: Events) { this.events = events; } logout() { this.events.publish('user:logout'); } } @App({ templateUrl: 'main.html' }) class ApiDemoApp { constructor(app: IonicApp, events: Events) { this.app = app; this.events = events; this.rootView = Login; this.loggedIn = false; this.pages = [ { title: 'Logout', component: Logout, showLoggedIn: true }, { title: 'Login', component: Login, showLoggedIn: false }, ]; this.listenToLoginEvents(); } openPage(menu, page) { // find the nav component and set what the root page should be // reset the nav to remove previous pages and only have this page // we wouldn't want the back button to show in this scenario let nav = this.app.getComponent('nav'); nav.setRoot(page.component); } listenToLoginEvents() { this.events.subscribe('user:login', () => { this.loggedIn = true; }); this.events.subscribe('user:logout', () => { this.loggedIn = false; }); } }
demos/events/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00019589648582041264, 0.00017343253421131521, 0.00016548053827136755, 0.00017052690964192152, 0.000009566299922880717 ]
{ "id": 2, "code_window": [ "\n", " let rg: RadioGroup;\n", " let form: Form;\n", "\n" ], "labels": [ "keep", "replace", "replace", "keep" ], "after_edit": [ " describe('RadioButton', () => {\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 89 }
## Ionic Framework 2.x The official npm package for [Ionic](http://ionicframework.com/) 2, complete with pre-built ES5 bundles, TypeScript definitions, Sass files, module-ready ES5 files, and more. To get started with Ionic 2, please read the [Installation](http://ionicframework.com/docs/v2/getting-started/installation/) guide. ### Source files In the root of the package are ES5 sources in the CommonJS module format, their associated Typescript type definition files, and the Ionic Sass entry files. The Javascript sources are meant to be used by a bundler such as Webpack, SystemJS Builder, or Browserify. The type definitions provide support to Typescript tooling for things like type checking and code completion. Usually, the only import required by the user is `ionic-angular`, as everything from Ionic is exported by the package: ``` import {App, Page} from 'ionic-angular'; ``` ### Bundles Minified and unminified CommonJS and System.register module format bundles, as well as compiled CSS stylesheets for both Ionic iOS and Material Design are located `bundles/`. The SystemJS bundle is primarily meant to be included in a `<script>` tag for demos, tests and Javascript playgrounds like [Plunker](http://plnkr.co/). ### Installation and More To use Ionic 2, we recommend installing and utilizing the [Ionic CLI](http://ionicframework.com/docs/v2/getting-started/installation/) which will help you create pre-configured Ionic apps. For full instructions on using Ionic 2, please visit the [Ionic 2 Documentation](http://ionicframework.com/docs/v2/)
scripts/npm/README.md
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017111636407207698, 0.00016813188267406076, 0.0001640122354729101, 0.00016926703392527997, 0.0000030092742235865444 ]
{ "id": 3, "code_window": [ "\n", " function createRadioButton() {\n", " return new RadioButton(form, null, rg);\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " describe('ngOnDestroy', () => {\n", " it('should work without a group', () => {\n", " let rb1 = createRadioButton(false);\n", " expect(() => rb1.ngOnDestroy()).not.toThrowError();\n", " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 92 }
import {Component, Optional, Input, Output, HostListener, EventEmitter, ViewEncapsulation} from 'angular2/core'; import {Form} from '../../util/form'; import {isTrueProperty, isPresent, isBlank, isCheckedProperty} from '../../util/util'; import {Item} from '../item/item'; import {ListHeader} from '../list/list'; import {RadioGroup} from './radio-group'; /** * @description * A radio button with a unique value. Note that all `<ion-radio>` * components must be wrapped within a `<ion-list radio-group>`, * and there must be at least two `<ion-radio>` components within * the radio group. * * See the [Angular 2 Docs](https://angular.io/docs/ts/latest/guide/forms.html) for * more info on forms and input. * * @usage * ```html * * <ion-item> * <ion-label>Radio Label</ion-label> * <ion-radio value="radio-value"></ion-radio> * </ion-item> * * ``` * @demo /docs/v2/demos/radio/ * @see {@link /docs/v2/components#radio Radio Component Docs} */ @Component({ selector: 'ion-radio', template: '<div class="radio-icon" [class.radio-checked]="_checked">' + '<div class="radio-inner"></div>' + '</div>' + '<button role="radio" ' + 'type="button" ' + 'category="item-cover" ' + '[id]="id" ' + '[attr.aria-checked]="_checked" ' + '[attr.aria-labelledby]="_labelId" ' + '[attr.aria-disabled]="_disabled" ' + 'class="item-cover">' + '</button>', host: { '[class.radio-disabled]': '_disabled' }, encapsulation: ViewEncapsulation.None, }) export class RadioButton { private _checked: boolean = false; private _disabled: boolean = false; private _labelId: string; private _value: any = null; /** * @private */ id: string; /** * @output {any} expression to be evaluated when selected */ @Output() select: EventEmitter<any> = new EventEmitter(); constructor( private _form: Form, @Optional() private _item: Item, @Optional() private _group: RadioGroup ) { _form.register(this); if (_group) { // register with the radiogroup this.id = 'rb-' + _group.add(this); } if (_item) { // register the input inside of the item // reset to the item's id instead of the radiogroup id this.id = 'rb-' + _item.registerInput('radio'); this._labelId = 'lbl-' + _item.id; this._item.setCssClass('item-radio', true); } } /** * @private */ @Input() get value(): any { // if the value is not defined then use it's unique id return isBlank(this._value) ? this.id : this._value; } set value(val: any) { this._value = val; } /** * @private */ @Input() get checked(): boolean { return this._checked; } set checked(isChecked: boolean) { this._checked = isTrueProperty(isChecked); if (this._item) { this._item.setCssClass('item-radio-checked', this._checked); } } /** * @private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(val: boolean) { this._disabled = isTrueProperty(val); this._item && this._item.setCssClass('item-radio-disabled', this._disabled); } /** * @private */ @HostListener('click', ['$event']) private _click(ev) { console.debug('radio, select', this.id); ev.preventDefault(); ev.stopPropagation(); this.checked = true; this.select.emit(this.value); } /** * @private */ ngOnInit() { if (this._group && isPresent(this._group.value)) { this.checked = isCheckedProperty(this._group.value, this.value); } } /** * @private */ ngOnDestroy() { this._form.deregister(this); this._group.remove(this); } }
ionic/components/radio/radio-button.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.001721192616969347, 0.0003325091674923897, 0.00016529634012840688, 0.00017249111260753125, 0.0003885605838149786 ]
{ "id": 3, "code_window": [ "\n", " function createRadioButton() {\n", " return new RadioButton(form, null, rg);\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " describe('ngOnDestroy', () => {\n", " it('should work without a group', () => {\n", " let rb1 = createRadioButton(false);\n", " expect(() => rb1.ngOnDestroy()).not.toThrowError();\n", " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 92 }
import {App, IonicApp} from '../../../../../ionic'; @App({ templateUrl: 'main.html' }) class E2EApp { constructor(app: IonicApp) { } }
ionic/components/chip/test/image/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001798125304048881, 0.00017441375530324876, 0.0001690149656496942, 0.00017441375530324876, 0.0000053987823775969446 ]
{ "id": 3, "code_window": [ "\n", " function createRadioButton() {\n", " return new RadioButton(form, null, rg);\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " describe('ngOnDestroy', () => {\n", " it('should work without a group', () => {\n", " let rb1 = createRadioButton(false);\n", " expect(() => rb1.ngOnDestroy()).not.toThrowError();\n", " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 92 }
<ion-navbar *navbar> <ion-title>Virtual Scroll</ion-title> <ion-buttons end> <button (click)="reload()"> Reload </button> </ion-buttons> </ion-navbar> <ion-content> <ion-list [virtualScroll]="items" [headerFn]="headerFn"> <ion-item-divider *virtualHeader="#header"> Header: {{header}} </ion-item-divider> <ion-item *virtualItem="#item"> Item: {{item}} </ion-item> </ion-list> </ion-content>
ionic/components/virtual-scroll/test/basic/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017573116929270327, 0.00017114431830123067, 0.00016869761748239398, 0.00016900416812859476, 0.0000032458069654239807 ]
{ "id": 3, "code_window": [ "\n", " function createRadioButton() {\n", " return new RadioButton(form, null, rg);\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " describe('ngOnDestroy', () => {\n", " it('should work without a group', () => {\n", " let rb1 = createRadioButton(false);\n", " expect(() => rb1.ngOnDestroy()).not.toThrowError();\n", " });\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 92 }
@import "../../globals.wp"; @import "./toast"; // Windows Phone Toast // -------------------------------------------------- $toast-wp-text-align: left !default; $toast-wp-background: rgba(0, 0, 0, 1) !default; $toast-wp-border-radius: 0 !default; $toast-wp-button-color: #fff !default; $toast-wp-title-color: #fff !default; $toast-wp-title-font-size: 1.4rem !default; $toast-wp-title-padding: 1.5rem !default; .toast-wrapper { position: absolute; bottom: 0; left: 0; z-index: $z-index-overlay-wrapper; display: block; margin: auto; max-width: $toast-max-width; border-radius: $toast-wp-border-radius; background: $toast-wp-background; transform: translate3d(0, 100%, 0); } .toast-message { padding: $toast-wp-title-padding; font-size: $toast-wp-title-font-size; color: $toast-wp-title-color; } .toast-button { color: $toast-wp-button-color; }
ionic/components/toast/toast.wp.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0013888016110286117, 0.0004131550376769155, 0.00016722788859624416, 0.00017072114860638976, 0.0004878261242993176 ]
{ "id": 4, "code_window": [ "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " it('should remove button from group if part of a radio group', () => {\n", " let rb1 = createRadioButton();\n", " spyOn(rg, 'remove');\n", " rb1.ngOnDestroy();\n", " expect(rg.remove).toHaveBeenCalledWith(rb1);\n", " });\n", "\n", " });\n", "\n", " });\n", "\n", " let rg: RadioGroup;\n", " let form: Form;\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 96 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.999202311038971, 0.14972876012325287, 0.00016634953499305993, 0.00016987387789413333, 0.3369898200035095 ]
{ "id": 4, "code_window": [ "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " it('should remove button from group if part of a radio group', () => {\n", " let rb1 = createRadioButton();\n", " spyOn(rg, 'remove');\n", " rb1.ngOnDestroy();\n", " expect(rg.remove).toHaveBeenCalledWith(rb1);\n", " });\n", "\n", " });\n", "\n", " });\n", "\n", " let rg: RadioGroup;\n", " let form: Form;\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 96 }
$font-path: "../fonts"; $roboto-font-path: "../fonts"; // http://ionicframework.com/docs/v2/theming/ // App Shared Variables // -------------------------------------------------- // To customize the look and feel of this app, you can override // the Sass variables found in Ionic's source scss files. Setting // variables before Ionic's Sass will use these variables rather than // Ionic's default Sass variable values. App Shared Sass imports belong // in the app.core.scss file and not this file. Sass variables specific // to the mode belong in either the app.ios.scss or app.md.scss files. // App Shared Color Variables // -------------------------------------------------- // It's highly recommended to change the default colors // to match your app's branding. Ionic uses a Sass map of // colors so you can add, rename and remove colors as needed. // The "primary" color is the only required color in the map. // Both iOS and MD colors can be further customized if colors // are different per mode. $colors: ( primary: #387ef5, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, vibrant: rebeccapurple, bright: #FFC125 ); @import "../ionic/ionic.ios";
demos/output.ios.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017142501019407064, 0.0001689233467914164, 0.00016710819909349084, 0.0001685800962150097, 0.0000016377869087591534 ]
{ "id": 4, "code_window": [ "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " it('should remove button from group if part of a radio group', () => {\n", " let rb1 = createRadioButton();\n", " spyOn(rg, 'remove');\n", " rb1.ngOnDestroy();\n", " expect(rg.remove).toHaveBeenCalledWith(rb1);\n", " });\n", "\n", " });\n", "\n", " });\n", "\n", " let rg: RadioGroup;\n", " let form: Form;\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 96 }
<ion-slides loop="true" style="background-color: black"> <ion-slide *ngFor="#image of [1,2,3,4,5]"> <img data-src="./slide{{image}}.jpeg"> </ion-slide> </ion-slides>
demos/slides/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018269519205205142, 0.00018269519205205142, 0.00018269519205205142, 0.00018269519205205142, 0 ]
{ "id": 4, "code_window": [ "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " it('should remove button from group if part of a radio group', () => {\n", " let rb1 = createRadioButton();\n", " spyOn(rg, 'remove');\n", " rb1.ngOnDestroy();\n", " expect(rg.remove).toHaveBeenCalledWith(rb1);\n", " });\n", "\n", " });\n", "\n", " });\n", "\n", " let rg: RadioGroup;\n", " let form: Form;\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 96 }
@import "../../globals.core"; // Modals // -------------------------------------------------- ion-page.modal { z-index: $z-index-overlay; // hidden by default to prevent flickers, the animation will show it transform: translate3d(0, 100%, 0); }
ionic/components/modal/modal.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018285936675965786, 0.00017651917005423456, 0.00017017897334881127, 0.00017651917005423456, 0.0000063401967054232955 ]
{ "id": 5, "code_window": [ "\n", " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function createRadioButton(shouldIncludeGroup = true) {\n", " return new RadioButton(form, null, shouldIncludeGroup? rg : null);\n", " }\n", "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 102 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.9988086223602295, 0.08448729664087296, 0.00016732326184865087, 0.00017050903989002109, 0.2757020592689514 ]
{ "id": 5, "code_window": [ "\n", " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function createRadioButton(shouldIncludeGroup = true) {\n", " return new RadioButton(form, null, shouldIncludeGroup? rg : null);\n", " }\n", "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 102 }
<!-- Generated template for the <%= jsClassName %> page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. --> <ion-navbar *navbar> <ion-title><%= name %></ion-title> </ion-navbar> <ion-content padding class="<%= fileName %>"> </ion-content>
tooling/generators/page/page.tmpl.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00016795193369034678, 0.0001671297213761136, 0.0001663075090618804, 0.0001671297213761136, 8.222123142331839e-7 ]
{ "id": 5, "code_window": [ "\n", " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function createRadioButton(shouldIncludeGroup = true) {\n", " return new RadioButton(form, null, shouldIncludeGroup? rg : null);\n", " }\n", "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 102 }
import {Activator} from './activator'; import {CSS, nativeRaf, rafFrames} from '../../util/dom'; const win: any = window; /** * @private */ export class RippleActivator extends Activator { constructor(app, config, zone) { super(app, config, zone); } downAction(ev, activatableEle, pointerX, pointerY) { let self = this; if (self.disableActivated(ev)) { return; } // queue to have this element activated self._queue.push(activatableEle); this._zone.runOutsideAngular(function() { nativeRaf(function() { var i; for (i = 0; i < self._queue.length; i++) { var queuedEle = self._queue[i]; if (queuedEle && queuedEle.parentNode) { self._active.push(queuedEle); // DOM WRITE queuedEle.classList.add(self._css); var j = queuedEle.childElementCount; while (j--) { var rippleEle: any = queuedEle.children[j]; if (rippleEle.tagName === 'ION-BUTTON-EFFECT') { // DOM WRITE rippleEle.style.left = '-9999px'; rippleEle.style.opacity = ''; rippleEle.style[CSS.transform] = 'scale(0.001) translateZ(0px)'; rippleEle.style[CSS.transition] = ''; // DOM READ var clientRect = activatableEle.getBoundingClientRect(); rippleEle.$top = clientRect.top; rippleEle.$left = clientRect.left; rippleEle.$width = clientRect.width; rippleEle.$height = clientRect.height; break; } } } } self._queue = []; }); }); } upAction(ev: UIEvent, activatableEle: HTMLElement, pointerX: number, pointerY: number) { let self = this; var i = activatableEle.childElementCount; while (i--) { var rippleEle: any = activatableEle.children[i]; if (rippleEle.tagName === 'ION-BUTTON-EFFECT') { var clientPointerX = (pointerX - rippleEle.$left); var clientPointerY = (pointerY - rippleEle.$top); var x = Math.max(Math.abs(rippleEle.$width - clientPointerX), clientPointerX) * 2; var y = Math.max(Math.abs(rippleEle.$height - clientPointerY), clientPointerY) * 2; var diameter = Math.min(Math.max(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)), 64), 240); if (activatableEle.hasAttribute('ion-item')) { diameter = Math.min(diameter, 140); } var radius = Math.sqrt(rippleEle.$width + rippleEle.$height); var scaleTransitionDuration = Math.max(1600 * Math.sqrt(radius / TOUCH_DOWN_ACCEL) + 0.5, 260); var opacityTransitionDuration = scaleTransitionDuration * 0.7; var opacityTransitionDelay = scaleTransitionDuration - opacityTransitionDuration; // DOM WRITE rippleEle.style.width = rippleEle.style.height = diameter + 'px'; rippleEle.style.marginTop = rippleEle.style.marginLeft = -(diameter / 2) + 'px'; rippleEle.style.left = clientPointerX + 'px'; rippleEle.style.top = clientPointerY + 'px'; rippleEle.style.opacity = '0'; rippleEle.style[CSS.transform] = 'scale(1) translateZ(0px)'; rippleEle.style[CSS.transition] = 'transform ' + scaleTransitionDuration + 'ms,opacity ' + opacityTransitionDuration + 'ms ' + opacityTransitionDelay + 'ms'; } } super.upAction(ev, activatableEle, pointerX, pointerY); } deactivate() { // remove the active class from all active elements let self = this; self._queue = []; rafFrames(2, function() { for (var i = 0; i < self._active.length; i++) { self._active[i].classList.remove(self._css); } self._active = []; }); } } const TOUCH_DOWN_ACCEL = 300;
ionic/components/tap-click/ripple.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0029043753165751696, 0.0008125379681587219, 0.0001649798359721899, 0.00016871289699338377, 0.0010574936168268323 ]
{ "id": 5, "code_window": [ "\n", " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function createRadioButton(shouldIncludeGroup = true) {\n", " return new RadioButton(form, null, shouldIncludeGroup? rg : null);\n", " }\n", "\n", " function mockRenderer(): any {\n", " return {\n", " setElementAttribute: function(){}\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 102 }
<ion-navbar *navbar> <ion-title>Config</ion-title> </ion-navbar> <ion-content class="config-demo"> <ion-list> <ion-item> <ion-label>Back Button Icon</ion-label> <ion-select [(ngModel)]="config.backButtonIcon"> <ion-option value="ios-arrow-back">ios-arrow-back</ion-option> <ion-option value="md-arrow-back">md-arrow-back</ion-option> <ion-option value="close">close</ion-option> <ion-option value="heart">heart</ion-option> <ion-option value="globe">globe</ion-option> </ion-select> </ion-item> <ion-item> <ion-label>Icon Mode</ion-label> <ion-select [(ngModel)]="config.iconMode"> <ion-option value="ios">ios</ion-option> <ion-option value="md">md</ion-option> </ion-select> </ion-item> <ion-item> <ion-label>Tab Placement</ion-label> <ion-select [(ngModel)]="config.tabbarPlacement"> <ion-option value="bottom">bottom</ion-option> <ion-option value="top">top</ion-option> </ion-select> </ion-item> </ion-list> <p class="note">Note: the config will not be updated until you click the button below.</p> <div padding> <button block (click)="load()"> Update Config </button> </div> <!-- this has to be formatted weird for pre --> <pre margin>@App({ config: { backButtonIcon: {{initialConfig.backButtonIcon}} iconMode: {{initialConfig.iconMode}} tabbarPlacement: {{initialConfig.tabbarPlacement}} } })</pre> <div padding> <button block secondary (click)="push()"> Go to Another Page </button> </div> </ion-content> <style> .config-demo pre { background-color: #f8f8f8; } .config-demo .note { color: #444; font-style: italic; margin: 0 16px; } </style>
demos/config/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018162337073590606, 0.00017169484635815024, 0.00016618100926280022, 0.0001721110165817663, 0.000004669910140364664 ]
{ "id": 6, "code_window": [ " }\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 107 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.03002067655324936, 0.0027861662674695253, 0.00016606030112598091, 0.0002319778868695721, 0.00821396429091692 ]
{ "id": 6, "code_window": [ " }\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 107 }
@import "../../globals.wp"; // Windows Menu // -------------------------------------------------- $menu-wp-background: #f2f2f2 !default; ion-menu { background: $menu-wp-background; }
ionic/components/menu/menu.wp.scss
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001851577399065718, 0.0001849069376476109, 0.00018465614994056523, 0.0001849069376476109, 2.507949830032885e-7 ]
{ "id": 6, "code_window": [ " }\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 107 }
<ion-toolbar> <ion-title>Chips With Icon</ion-title> </ion-toolbar> <ion-content padding style="text-align:center"> <p> <ion-chip> <ion-icon name="pin"></ion-icon> <ion-label>Default</ion-label> </ion-chip> </p> <p> <ion-chip> <ion-icon name="pin" primary></ion-icon> <ion-label>Primary</ion-label> </ion-chip> </p> <p> <ion-chip> <ion-icon name="pin" secondary></ion-icon> <ion-label>Secondary</ion-label> </ion-chip> </p> <p> <ion-chip> <ion-icon name="pin" danger></ion-icon> <ion-label>Danger</ion-label> </ion-chip> </p> <p> <ion-chip> <ion-icon name="pin" light></ion-icon> <ion-label>Light</ion-label> </ion-chip> </p> <p> <ion-chip> <ion-icon name="pin" dark></ion-icon> <ion-label>Dark</ion-label> </ion-chip> </p> </ion-content>
ionic/components/chip/test/icon/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0022862092591822147, 0.0008742019417695701, 0.00031297068926505744, 0.0005927220918238163, 0.0007253558142110705 ]
{ "id": 6, "code_window": [ " }\n", "\n" ], "labels": [ "add", "keep" ], "after_edit": [ " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 107 }
ionic/components/button/test/sizes/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00018765385902952403, 0.00018765385902952403, 0.00018765385902952403, 0.00018765385902952403, 0 ]
{ "id": 7, "code_window": [ "\n", " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n", " });\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 108 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.9657469987869263, 0.40189793705940247, 0.00016366153431590647, 0.11074735224246979, 0.4372922480106354 ]
{ "id": 7, "code_window": [ "\n", " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n", " });\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 108 }
<ion-toolbar> <ion-title>Select Item: Multiple Value</ion-title> </ion-toolbar> <ion-content class="outer-content"> <ion-item> <ion-label>Toppings</ion-label> <ion-select [(ngModel)]="toppings" multiple="true" cancelText="Nah" okText="Okay!" class="e2eSelectToppings"> <ion-option value="bacon">Bacon</ion-option> <ion-option value="olives">Black Olives</ion-option> <ion-option value="xcheese">Extra Cheese</ion-option> <ion-option value="peppers">Green Peppers</ion-option> <ion-option value="mushrooms">Mushrooms</ion-option> <ion-option value="onions">Onions</ion-option> <ion-option value="pepperoni">Pepperoni</ion-option> <ion-option value="pineapple">Pineapple</ion-option> <ion-option value="sausage">Sausage</ion-option> <ion-option value="Spinach">Spinach</ion-option> </ion-select> </ion-item> <ion-item> <ion-label>Car Features</ion-label> <ion-select [(ngModel)]="carFeatures" [multiple]="true" (change)="carChange($event)"> <ion-option value="backupcamera">Backup Camera</ion-option> <ion-option value="heatedseats">Headted Seats</ion-option> <ion-option value="keyless">Keyless Entry</ion-option> <ion-option value="navigation">Navigation</ion-option> <ion-option value="parkingassist">Parking Assist</ion-option> <ion-option value="sunroof">Sun Roof</ion-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select [(ngModel)]="pets" multiple> <ion-option *ngFor="#o of petOptions" [value]="o.value">{{o.text}}</ion-option> </ion-select> </ion-item> <ion-item> <ion-label>Disabled</ion-label> <ion-select multiple disabled> <ion-option checked="true">Selected Text</ion-option> </ion-select> </ion-item> <p aria-hidden="true" padding> <code>toppings: {{toppings}}</code><br> <code>carFeatures: {{carFeatures}}</code><br> <code>pets: {{pets}}</code><br> </p> <form [ngFormModel]="authForm" (ngSubmit)="onSubmit(authForm.value)"> <ion-list padding-vertical> <ion-item> <ion-input ngControl="name" type="text"></ion-input> </ion-item> <ion-item class="no-border"> <ion-label>Select</ion-label> <ion-select multiple="true" ngControl="select"> <ion-option>1</ion-option> <ion-option>2</ion-option> <ion-option>3</ion-option> </ion-select> </ion-item> <button full block class="no-margin" type="submit">Submit</button> </ion-list> </form> </ion-content>
ionic/components/select/test/multiple-value/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0001739671133691445, 0.00016849854728206992, 0.00016521362704224885, 0.00016736859106458724, 0.0000031710610528534744 ]
{ "id": 7, "code_window": [ "\n", " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n", " });\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 108 }
import {Directive, Component, ElementRef, Renderer, Optional, EventEmitter, Input, Output, HostListener, ContentChildren, QueryList, ViewEncapsulation} from 'angular2/core'; import {NgControl} from 'angular2/common'; import {isTrueProperty, isPresent} from '../../util/util'; /** * @name SegmentButton * @description * The child buttons of the `ion-segment` component. Each `ion-segment-button` must have a value. * @usage * ```html * <ion-segment [(ngModel)]="relationship" primary> * <ion-segment-button value="friends" (select)="selectedFriends()"> * Friends * </ion-segment-button> * <ion-segment-button value="enemies" (select)="selectedEnemies()"> * Enemies * </ion-segment-button> * </ion-segment> *``` * * Or with `FormBuilder` * *```html * <form [ngFormModel]="myForm"> * <ion-segment ngControl="mapStyle" danger> * <ion-segment-button value="standard"> * Standard * </ion-segment-button> * <ion-segment-button value="hybrid"> * Hybrid * </ion-segment-button> * <ion-segment-button value="sat"> * Satellite * </ion-segment-button> * </ion-segment> * </form> * ``` * * * @demo /docs/v2/demos/segment/ * @see {@link /docs/v2/components#segment Segment Component Docs} * @see {@link /docs/v2/api/components/segment/Segment/ Segment API Docs} */ @Component({ selector: 'ion-segment-button', template: '<ng-content></ng-content>' + '<ion-button-effect></ion-button-effect>', host: { 'tappable': '', 'class': 'segment-button', 'role': 'button' }, encapsulation: ViewEncapsulation.None, }) export class SegmentButton { private _disabled: boolean = false; /** * @input {string} the value of the segment button. Required. */ @Input() value: string; /** * @output {SegmentButton} expression to evaluate when a segment button has been clicked */ @Output() select: EventEmitter<SegmentButton> = new EventEmitter(); constructor(private _renderer: Renderer, private _elementRef: ElementRef) {} /** * @private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(val: boolean) { this._disabled = isTrueProperty(val); this.setCssClass('segment-button-disabled', this._disabled); } /** * @private */ setCssClass(cssClass: string, shouldAdd: boolean) { this._renderer.setElementClass(this._elementRef.nativeElement, cssClass, shouldAdd); } /** * @private * On click of a SegmentButton */ @HostListener('click', ['$event']) private onClick(ev) { console.debug('SegmentButton, select', this.value); this.select.emit(this); } /** * @private */ ngOnInit() { if (!isPresent(this.value)) { console.warn('<ion-segment-button> requires a "value" attribute'); } } /** * @private */ set isActive(isActive) { this._renderer.setElementClass(this._elementRef.nativeElement, 'segment-activated', isActive); this._renderer.setElementAttribute(this._elementRef.nativeElement, 'aria-pressed', isActive); } } /** * @name Segment * @description * A Segment is a group of buttons, sometimes known as Segmented Controls, that allow the user to interact with a compact group of a number of controls. * Segments provide functionality similar to tabs, selecting one will unselect all others. You should use a tab bar instead of a segmented control when you want to let the user move back and forth between distinct pages in your app. * You could use Angular 2's `ngModel` or `FormBuilder` API. For an overview on how `FormBuilder` works, checkout [Angular 2 Forms](http://learnangular2.com/forms/), or [Angular FormBuilder](https://angular.io/docs/ts/latest/api/common/FormBuilder-class.html) * * * @usage * ```html * <ion-segment [(ngModel)]="relationship" (change)="onSegmentChanged($event)" danger> * <ion-segment-button value="friends"> * Friends * </ion-segment-button> * <ion-segment-button value="enemies"> * Enemies * </ion-segment-button> * </ion-segment> *``` * * Or with `FormBuilder` * *```html * <form [ngFormModel]="myForm"> * <ion-segment ngControl="mapStyle" danger> * <ion-segment-button value="standard"> * Standard * </ion-segment-button> * <ion-segment-button value="hybrid"> * Hybrid * </ion-segment-button> * <ion-segment-button value="sat"> * Satellite * </ion-segment-button> * </ion-segment> * </form> * ``` * * * @demo /docs/v2/demos/segment/ * @see {@link /docs/v2/components#segment Segment Component Docs} * @see [Angular 2 Forms](http://learnangular2.com/forms/) */ @Directive({ selector: 'ion-segment' }) export class Segment { private _disabled: boolean = false; /** * @private */ value: string; /** * @output {Any} expression to evaluate when a segment button has been changed */ @Output() change: EventEmitter<SegmentButton> = new EventEmitter(); /** * @private */ @ContentChildren(SegmentButton) _buttons: QueryList<SegmentButton>; constructor(@Optional() ngControl: NgControl) { if (ngControl) { ngControl.valueAccessor = this; } } /** * @private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(val: boolean) { this._disabled = isTrueProperty(val); if (this._buttons) { let buttons = this._buttons.toArray(); for (let button of buttons) { button.setCssClass('segment-button-disabled', this._disabled); } } } /** * @private * Write a new value to the element. */ writeValue(value) { this.value = isPresent(value) ? value : ''; if (this._buttons) { let buttons = this._buttons.toArray(); for (let button of buttons) { button.isActive = (button.value === this.value); } } } /** * @private */ ngAfterViewInit() { let buttons = this._buttons.toArray(); for (let button of buttons) { button.select.subscribe((selectedButton) => { this.writeValue(selectedButton.value); this.onChange(selectedButton.value); this.change.emit(selectedButton); }); if (isPresent(this.value)) { button.isActive = (button.value === this.value); } if (isTrueProperty(this._disabled)) { button.setCssClass('segment-button-disabled', this._disabled); } } } /** * @private */ onChange = (_) => {}; /** * @private */ onTouched = (_) => {}; /** * @private * Set the function to be called when the control receives a change event. */ registerOnChange(fn) { this.onChange = fn; } /** * @private * Set the function to be called when the control receives a touch event. */ registerOnTouched(fn) { this.onTouched = fn; } }
ionic/components/segment/segment.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017921139078680426, 0.00017006983398459852, 0.00016475521260872483, 0.0001694661914370954, 0.0000034939550914714346 ]
{ "id": 7, "code_window": [ "\n", " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n", " });\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " function mockElementRef(): any {\n", " return {\n", " nativeElement: document.createElement('div')\n", " }\n", " }\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "replace", "edit_start_line_idx": 108 }
<select name="version" id="version-toggle" onchange="window.location.href=this.options[this.selectedIndex].value"> <@ for ver in version.list @> <option value="<$ ver.href $>/{% if page.path != ''%}{{page.path}}{% else %}api/{% endif %}" {% if page.version == "<$ ver.name $>"%}selected{% endif %}> <@ if ver.name == "nightly" @>2.0.0-<@ endif @><$ ver.name $> <@ if version.latest.name == ver.name @>(latest)<@ endif @> </option> <@ endfor @> </select>
scripts/docs/templates/api_version_select.template.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00017696300346869975, 0.00017691156244836748, 0.00017686010687611997, 0.00017691156244836748, 5.1448296289891005e-8 ]
{ "id": 8, "code_window": [ "\n", " });\n", "}" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 113 }
import {RadioGroup, RadioButton, Form} from '../../../../ionic'; export function run() { describe('RadioGroup', () => { describe('_update', () => { it('should set checked via string values', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string2'; let rb3 = createRadioButton(); rb3.value = 'string3'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via string group value, and number button values', () => { let rb1 = createRadioButton(); rb1.value = 1; let rb2 = createRadioButton(); rb2.value = 2; let rb3 = createRadioButton(); rb3.value = 3; rg.value = '1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via number group value, and string button values', () => { let rb1 = createRadioButton(); rb1.value = '1'; let rb2 = createRadioButton(); rb2.value = '2'; let rb3 = createRadioButton(); rb3.value = '3'; rg.value = 1; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should set checked via empty string group value, and one empty string button value', () => { let rb1 = createRadioButton(); rb1.value = ''; let rb2 = createRadioButton(); rb2.value = 'value2'; let rb3 = createRadioButton(); rb3.value = 'value3'; rg.value = ''; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); it('should only check at most one value', () => { let rb1 = createRadioButton(); rb1.value = 'string1'; let rb2 = createRadioButton(); rb2.value = 'string1'; let rb3 = createRadioButton(); rb3.value = 'string1'; rg.value = 'string1'; rg._update(); expect(rb1.checked).toEqual(true); expect(rb2.checked).toEqual(false); expect(rb3.checked).toEqual(false); }); }); let rg: RadioGroup; let form: Form; function createRadioButton() { return new RadioButton(form, null, rg); } function mockRenderer(): any { return { setElementAttribute: function(){} } } function mockElementRef(): any { return { nativeElement: document.createElement('div') } } beforeEach(() => { rg = new RadioGroup(mockRenderer(), mockElementRef()); form = new Form(); }); }); }
ionic/components/radio/test/radio.spec.ts
1
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.9349860548973083, 0.07824838161468506, 0.000175104767549783, 0.0003022062301170081, 0.2583162486553192 ]
{ "id": 8, "code_window": [ "\n", " });\n", "}" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 113 }
<ion-toolbar><ion-title>List Headers Borders</ion-title></ion-toolbar> <ion-content class="outer-content"> <ion-list class="outer-content" *ngFor="#person of people"> <ion-list-header> {{person.name}} </ion-list-header> <ion-item *ngFor="#component of person.components"> {{component}} <div item-right> <ion-icon name="pin"></ion-icon> </div> </ion-item> </ion-list> </ion-content>
ionic/components/list/test/repeat-headers/main.html
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.00024200291954912245, 0.0002082826104015112, 0.00017456231580581516, 0.0002082826104015112, 0.000033720301871653646 ]
{ "id": 8, "code_window": [ "\n", " });\n", "}" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 113 }
import {App, IonicApp} from '../../../../../ionic'; @App({ templateUrl: 'main.html' }) class E2EApp { constructor(app: IonicApp) { app.setTitle('Basic Buttons'); this.testingColors = ['primary', 'secondary', 'danger', 'dark']; this.testingColorIndex = 0; this.chgColor(); } chgColor() { this.btnColor = this.testingColors[this.testingColorIndex]; console.log('dynamic btnColor', this.btnColor); this.testingColorIndex = (this.testingColorIndex >= this.testingColors.length - 1 ? 0 : this.testingColorIndex + 1); } }
ionic/components/button/test/basic/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.0010253125801682472, 0.0004962683306075633, 0.00018787174485623837, 0.000275620783213526, 0.00037580207572318614 ]
{ "id": 8, "code_window": [ "\n", " });\n", "}" ], "labels": [ "add", "keep", "keep" ], "after_edit": [ " beforeEach(() => {\n", " rg = new RadioGroup(mockRenderer(), mockElementRef());\n", " form = new Form();\n" ], "file_path": "ionic/components/radio/test/radio.spec.ts", "type": "add", "edit_start_line_idx": 113 }
import {App, Page, IonicApp, Config, Platform} from 'ionic-angular'; import {Storage, LocalStorage} from 'ionic-angular'; import {Pipe, PipeTransform, Injectable} from 'angular2/core' @Pipe({name: 'cleanLocalData'}) @Injectable() class CleanLocalDataPipe implements PipeTransform { transform(obj:any) : any { this.validKeys = ['username', 'name', 'email', 'address']; this.output = {}; this.data = JSON.parse(obj); for (var i = 0; i < Object.keys(this.data).length; i++) { if (this.validKeys.indexOf( Object.keys(this.data)[i] ) > -1) { this.output[Object.keys(this.data)[i]] = this.data[Object.keys(this.data)[i]]; } } return JSON.stringify(this.output, null, 2); } } @App({ template: '<ion-nav [root]="root"></ion-nav>', pipes: [CleanLocalDataPipe] }) class ApiDemoApp { constructor() { this.root = MainPage; } } @Page({ templateUrl: 'main.html', pipes: [CleanLocalDataPipe] }) class MainPage { constructor() { this.local = new Storage(LocalStorage); this.localStorageDemo = '{}'; window.localStorage.clear(); this.myItem = { key: 'username', value: 'admin' }; this.keys = ['username', 'name', 'email', 'address']; this.values = ['admin', 'Administrator', '[email protected]', '123 Admin St']; this.addedKeys = []; } set() { if (this.myItem.key) { let added = false; for (let i = 0; i < this.addedKeys.length; i++) { if (this.addedKeys[i] == this.myItem.key) added = true; } if (added == false) { console.log("Adding key", this.myItem.key); this.addedKeys.push(this.myItem.key); this.delKey = this.myItem.key; this.local.set(this.myItem.key, this.myItem.value ); this.localStorageDemo = JSON.stringify(window.localStorage, null, 2); } } } remove() { this.local.remove(this.delKey); this.localStorageDemo = JSON.stringify(window.localStorage, null, 2); let index = this.addedKeys.indexOf(this.delKey); if (index > -1) { this.addedKeys.splice(index, 1); } } }
demos/local-storage/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/cf5ef7d258c0889719b672e152d5bd9d8c28861f
[ 0.038221608847379684, 0.006012243218719959, 0.0002141797885997221, 0.000777709879912436, 0.012271597050130367 ]
{ "id": 0, "code_window": [ "\tpadding: 0;\n", "}\n", "\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ ".search-view:not(.wide) .foldermatch .monaco-icon-label,\n", ".search-view:not(.wide) .filematch .monaco-icon-label {\n", "\tflex: 1;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "add", "edit_start_line_idx": 181 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .vs .panel .search-view .monaco-inputbox { border: 1px solid #ddd; } .search-view .search-widgets-container { margin: 0px 9px 0 2px; padding-top: 6px; } .search-view .search-widget .toggle-replace-button { position: absolute; top: 0; left: 0; width: 16px; height: 100%; box-sizing: border-box; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .search-view .search-widget .search-container, .search-view .search-widget .replace-container { margin-left: 17px; } .search-view .search-widget .input-box, .search-view .search-widget .input-box .monaco-inputbox { height: 25px; } .search-view .search-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .search-view .search-widget .replace-container { margin-top: 6px; position: relative; display: inline-flex; } .search-view .search-widget .replace-container.disabled { display: none; } .search-view .search-widget .replace-container .monaco-action-bar { margin-left: 3px; } .search-view .search-widget .replace-container .monaco-action-bar { height: 25px; } .search-view .search-widget .replace-container .monaco-action-bar .action-item .icon { background-repeat: no-repeat; width: 20px; height: 25px; } .search-view .query-clear { width: 20px; height: 20px; position: absolute; top: 3px; right: 3px; cursor: pointer; } .search-view .query-details { min-height: 1em; position: relative; margin: 0 0 0 17px; } .search-view .query-details .more { position: absolute; margin-right: 0.3em; right: 0; cursor: pointer; width: 16px; height: 13px; z-index: 2; /* Force it above the search results message, which has a negative top margin */ } .hc-black .monaco-workbench .search-view .query-details .more, .vs-dark .monaco-workbench .search-view .query-details .more { background: url('ellipsis-inverse.svg') top center no-repeat; } .vs .monaco-workbench .search-view .query-details .more { background: url('ellipsis.svg') top center no-repeat; } .search-view .query-details .file-types { display: none; } .search-view .query-details .file-types > .monaco-inputbox { width: 100%; height: 25px; } .search-view .query-details.more .file-types { display: inherit; } .search-view .query-details.more .file-types:last-child { padding-bottom: 10px; } .search-view .query-details .search-pattern-info { width: 16px; height: 16px; } .search-view .query-details .search-configure-exclusions { width: 16px; height: 16px; } .monaco-action-bar .action-label.search-configure-exclusions { margin-right: 2px; } .vs-dark .monaco-workbench .search-configure-exclusions, .hc-black .monaco-workbench .search-configure-exclusions { background: url('configure-inverse.svg') center center no-repeat; opacity: .7; } .vs .monaco-workbench .search-configure-exclusions { background: url('configure.svg') center center no-repeat; opacity: 0.7; } .search-view .query-details.more h4 { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; padding: 4px 0 0; margin: 0; font-size: 11px; font-weight: normal; } .search-view .messages { margin-top: -5px; cursor: default; } .search-view .message { padding-left: 22px; padding-right: 22px; padding-top: 0px; } .search-view .message p:first-child { margin-top: 0px; margin-bottom: 0px; padding-bottom: 4px; user-select: text; } .search-view > .results > .monaco-tree .sub-content { overflow: hidden; } .search-view .foldermatch, .search-view .filematch { display: flex; position: relative; line-height: 22px; padding: 0; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .filematch .monaco-icon-label { flex: 1; } .search-view .foldermatch .directory, .search-view .filematch .directory { opacity: 0.7; font-size: 0.9em; margin-left: 0.8em; } .search-view .foldermatch .badge, .search-view .filematch .badge { margin-left: 10px; } .search-view .linematch { position: relative; line-height: 22px; display: flex; } .search-view .linematch > .match { flex: 1; overflow: hidden; text-overflow: ellipsis; } .search-view .linematch.changedOrRemoved { font-style: italic; } .search-view .query-clear { background: url("action-query-clear.svg") center center no-repeat; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar { line-height: 1em; display: none; padding: 0 0.8em 0 0.4em; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-item { margin: 0; } .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: 0; /* in order to support a11y with keyboard, we use width: 0 to hide the actions, which still allows to "Tab" into the actions */ display: block; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .monaco-action-bar, .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: inherit; display: block; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-label { margin-right: 0.2em; margin-top: 4px; background-repeat: no-repeat; width: 16px; height: 16px; } .search-view .action-remove { background: url("action-remove.svg") center center no-repeat; } .search-view .action-replace { background-image: url('replace.svg'); } .search-view .action-replace-all { background: url('replace-all.svg') center center no-repeat; } .hc-black .search-view .action-replace, .vs-dark .search-view .action-replace { background-image: url('replace-inverse.svg'); } .hc-black .search-view .action-replace-all, .vs-dark .search-view .action-replace-all { background: url('replace-all-inverse.svg') center center no-repeat; } .search-view .label { font-style: italic; } .search-view .monaco-count-badge { margin-right: 12px; } .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .linematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .linematch .monaco-count-badge { display: none; } .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove, .vs-dark .monaco-workbench .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove { background: url("action-remove-focus.svg") center center no-repeat; } .monaco-workbench .search-action.refresh { background: url('Refresh.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.refresh, .hc-black .monaco-workbench .search-action.refresh { background: url('Refresh_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.collapse { background: url('CollapseAll.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.collapse, .hc-black .monaco-workbench .search-action.collapse { background: url('CollapseAll_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.clear-search-results, .hc-black .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results-dark.svg') center center no-repeat; } .monaco-workbench .search-action.cancel-search { background: url('stop.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.cancel-search, .hc-black .monaco-workbench .search-action.cancel-search { background: url('stop-inverse.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern, .hc-black .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern-dark.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles, .hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings-dark.svg') center center no-repeat; } .search-view .replace.findInFileMatch { text-decoration: line-through; } .search-view .findInFileMatch, .search-view .replaceMatch { white-space: pre; } .hc-black .monaco-workbench .search-view .replaceMatch, .hc-black .monaco-workbench .search-view .findInFileMatch { background: none !important; box-sizing: border-box; } .monaco-workbench .search-view a.prominent { text-decoration: underline; } /* Theming */ .vs .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(0, 0, 0, 0.1) !important; } .vs-dark .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(255, 255, 255, 0.1) !important; } .vs .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed.svg'); } .vs .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded.svg'); } .vs-dark .search-view .query-clear { background: url("action-query-clear-dark.svg") center center no-repeat; } .vs-dark .search-view .action-remove, .hc-black .search-view .action-remove { background: url("action-remove-dark.svg") center center no-repeat; } .vs-dark .search-view .message { opacity: .5; } .vs-dark .search-view .foldermatch, .vs-dark .search-view .filematch { padding: 0; } .vs-dark .search-view .search-widget .toggle-replace-button.expand, .hc-black .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded-dark.svg'); } .vs-dark .search-view .search-widget .toggle-replace-button.collapse, .hc-black .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed-dark.svg'); } /* High Contrast Theming */ .hc-black .monaco-workbench .search-view .foldermatch, .hc-black .monaco-workbench .search-view .filematch, .hc-black .monaco-workbench .search-view .linematch { line-height: 20px; }
src/vs/workbench/parts/search/browser/media/searchview.css
1
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.042763322591781616, 0.002963219303637743, 0.00016518351912964135, 0.00023286875511985272, 0.008814899250864983 ]
{ "id": 0, "code_window": [ "\tpadding: 0;\n", "}\n", "\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ ".search-view:not(.wide) .foldermatch .monaco-icon-label,\n", ".search-view:not(.wide) .filematch .monaco-icon-label {\n", "\tflex: 1;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "add", "edit_start_line_idx": 181 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //#region Add support for using node_modules.asar (function () { const path = require('path'); const Module = require('module'); const NODE_MODULES_PATH = path.join(__dirname, '../node_modules'); const NODE_MODULES_ASAR_PATH = NODE_MODULES_PATH + '.asar'; const originalResolveLookupPaths = Module._resolveLookupPaths; Module._resolveLookupPaths = function (request, parent, newReturn) { const result = originalResolveLookupPaths(request, parent, newReturn); const paths = newReturn ? result : result[1]; for (let i = 0, len = paths.length; i < len; i++) { if (paths[i] === NODE_MODULES_PATH) { paths.splice(i, 0, NODE_MODULES_ASAR_PATH); break; } } return result; }; })(); //#endregion // Will be defined if we got forked from another node process // In that case we override console.log/warn/error to be able // to send loading issues to the main side for logging. if (!!process.send && process.env.PIPE_LOGGING === 'true') { var MAX_LENGTH = 100000; // Prevent circular stringify and convert arguments to real array function safeToArray(args) { var seen = []; var res; var argsArray = []; // Massage some arguments with special treatment if (args.length) { for (var i = 0; i < args.length; i++) { // Any argument of type 'undefined' needs to be specially treated because // JSON.stringify will simply ignore those. We replace them with the string // 'undefined' which is not 100% right, but good enough to be logged to console if (typeof args[i] === 'undefined') { args[i] = 'undefined'; } // Any argument that is an Error will be changed to be just the error stack/message // itself because currently cannot serialize the error over entirely. else if (args[i] instanceof Error) { var errorObj = args[i]; if (errorObj.stack) { args[i] = errorObj.stack; } else { args[i] = errorObj.toString(); } } argsArray.push(args[i]); } } // Add the stack trace as payload if we are told so. We remove the message and the 2 top frames // to start the stacktrace where the console message was being written if (process.env.VSCODE_LOG_STACK === 'true') { const stack = new Error().stack; argsArray.push({ __$stack: stack.split('\n').slice(3).join('\n') }); } try { res = JSON.stringify(argsArray, function (key, value) { // Objects get special treatment to prevent circles if (value && Object.prototype.toString.call(value) === '[object Object]') { if (seen.indexOf(value) !== -1) { return Object.create(null); // prevent circular references! } seen.push(value); } return value; }); } catch (error) { return 'Output omitted for an object that cannot be inspected (' + error.toString() + ')'; } if (res && res.length > MAX_LENGTH) { return 'Output omitted for a large object that exceeds the limits'; } return res; } function safeSend(arg) { try { process.send(arg); } catch (error) { // Can happen if the parent channel is closed meanwhile } } // Pass console logging to the outside so that we have it in the main side if told so if (process.env.VERBOSE_LOGGING === 'true') { console.log = function () { safeSend({ type: '__$console', severity: 'log', arguments: safeToArray(arguments) }); }; console.info = function () { safeSend({ type: '__$console', severity: 'log', arguments: safeToArray(arguments) }); }; console.warn = function () { safeSend({ type: '__$console', severity: 'warn', arguments: safeToArray(arguments) }); }; } else { console.log = function () { /* ignore */ }; console.warn = function () { /* ignore */ }; console.info = function () { /* ignore */ }; } console.error = function () { safeSend({ type: '__$console', severity: 'error', arguments: safeToArray(arguments) }); }; } if (!process.env['VSCODE_ALLOW_IO']) { // Let stdout, stderr and stdin be no-op streams. This prevents an issue where we would get an EBADF // error when we are inside a forked process and this process tries to access those channels. var stream = require('stream'); var writable = new stream.Writable({ write: function () { /* No OP */ } }); process.__defineGetter__('stdout', function () { return writable; }); process.__defineGetter__('stderr', function () { return writable; }); process.__defineGetter__('stdin', function () { return writable; }); } if (!process.env['VSCODE_HANDLES_UNCAUGHT_ERRORS']) { // Handle uncaught exceptions process.on('uncaughtException', function (err) { console.error('Uncaught Exception: ', err.toString()); if (err.stack) { console.error(err.stack); } }); } // Kill oneself if one's parent dies. Much drama. if (process.env['VSCODE_PARENT_PID']) { const parentPid = Number(process.env['VSCODE_PARENT_PID']); if (typeof parentPid === 'number' && !isNaN(parentPid)) { setInterval(function () { try { process.kill(parentPid, 0); // throws an exception if the main process doesn't exist anymore. } catch (e) { process.exit(); } }, 5000); } } const crashReporterOptionsRaw = process.env['CRASH_REPORTER_START_OPTIONS']; if (typeof crashReporterOptionsRaw === 'string') { try { const crashReporterOptions = JSON.parse(crashReporterOptionsRaw); if (crashReporterOptions) { process.crashReporter.start(crashReporterOptions); } } catch (error) { console.error(error); } } require('./bootstrap-amd').bootstrap(process.env['AMD_ENTRYPOINT']);
src/bootstrap.js
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017516988737042993, 0.00016911746934056282, 0.0001628855970920995, 0.00016855713329277933, 0.00000290485536424967 ]
{ "id": 0, "code_window": [ "\tpadding: 0;\n", "}\n", "\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ ".search-view:not(.wide) .foldermatch .monaco-icon-label,\n", ".search-view:not(.wide) .filematch .monaco-icon-label {\n", "\tflex: 1;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "add", "edit_start_line_idx": 181 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "textEditor": "텍스트 편집기", "readonlyEditorWithInputAriaLabel": "{0}. 읽기 전용 텍스트 편집기입니다.", "readonlyEditorAriaLabel": "읽기 전용 텍스트 편집기입니다.", "untitledFileEditorWithInputAriaLabel": "{0}. 제목 없는 파일 텍스트 편집기입니다.", "untitledFileEditorAriaLabel": "제목 없는 파일 텍스트 편집기입니다." }
i18n/kor/src/vs/workbench/browser/parts/editor/textResourceEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017225099145434797, 0.0001700091961538419, 0.00016776740085333586, 0.0001700091961538419, 0.0000022417953005060554 ]
{ "id": 0, "code_window": [ "\tpadding: 0;\n", "}\n", "\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label,\n", ".search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ ".search-view:not(.wide) .foldermatch .monaco-icon-label,\n", ".search-view:not(.wide) .filematch .monaco-icon-label {\n", "\tflex: 1;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "add", "edit_start_line_idx": 181 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "unknownDep": "无法激活扩展”{1}“。原因: 未知依赖关系“{0}”。", "failedDep1": "无法激活扩展”{1}“。原因: 无法激活依赖关系”{0}“。", "failedDep2": "无法激活扩展”{0}“。原因: 依赖关系多于 10 级(最可能是依赖关系循环)。", "activationError": "激活扩展“{0}”失败: {1}。" }
i18n/chs/src/vs/platform/extensions/common/abstractExtensionService.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017001936794258654, 0.00016834045527502894, 0.00016666152805555612, 0.00016834045527502894, 0.0000016789199435152113 ]
{ "id": 1, "code_window": [ "\tmargin-left: 0.8em;\n", "}\n", "\n", ".search-view .foldermatch .badge,\n", ".search-view .filematch .badge {\n", "\tmargin-left: 10px;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ ".search-view.wide .foldermatch .badge,\n", ".search-view.wide .filematch .badge {\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "replace", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .vs .panel .search-view .monaco-inputbox { border: 1px solid #ddd; } .search-view .search-widgets-container { margin: 0px 9px 0 2px; padding-top: 6px; } .search-view .search-widget .toggle-replace-button { position: absolute; top: 0; left: 0; width: 16px; height: 100%; box-sizing: border-box; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .search-view .search-widget .search-container, .search-view .search-widget .replace-container { margin-left: 17px; } .search-view .search-widget .input-box, .search-view .search-widget .input-box .monaco-inputbox { height: 25px; } .search-view .search-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .search-view .search-widget .replace-container { margin-top: 6px; position: relative; display: inline-flex; } .search-view .search-widget .replace-container.disabled { display: none; } .search-view .search-widget .replace-container .monaco-action-bar { margin-left: 3px; } .search-view .search-widget .replace-container .monaco-action-bar { height: 25px; } .search-view .search-widget .replace-container .monaco-action-bar .action-item .icon { background-repeat: no-repeat; width: 20px; height: 25px; } .search-view .query-clear { width: 20px; height: 20px; position: absolute; top: 3px; right: 3px; cursor: pointer; } .search-view .query-details { min-height: 1em; position: relative; margin: 0 0 0 17px; } .search-view .query-details .more { position: absolute; margin-right: 0.3em; right: 0; cursor: pointer; width: 16px; height: 13px; z-index: 2; /* Force it above the search results message, which has a negative top margin */ } .hc-black .monaco-workbench .search-view .query-details .more, .vs-dark .monaco-workbench .search-view .query-details .more { background: url('ellipsis-inverse.svg') top center no-repeat; } .vs .monaco-workbench .search-view .query-details .more { background: url('ellipsis.svg') top center no-repeat; } .search-view .query-details .file-types { display: none; } .search-view .query-details .file-types > .monaco-inputbox { width: 100%; height: 25px; } .search-view .query-details.more .file-types { display: inherit; } .search-view .query-details.more .file-types:last-child { padding-bottom: 10px; } .search-view .query-details .search-pattern-info { width: 16px; height: 16px; } .search-view .query-details .search-configure-exclusions { width: 16px; height: 16px; } .monaco-action-bar .action-label.search-configure-exclusions { margin-right: 2px; } .vs-dark .monaco-workbench .search-configure-exclusions, .hc-black .monaco-workbench .search-configure-exclusions { background: url('configure-inverse.svg') center center no-repeat; opacity: .7; } .vs .monaco-workbench .search-configure-exclusions { background: url('configure.svg') center center no-repeat; opacity: 0.7; } .search-view .query-details.more h4 { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; padding: 4px 0 0; margin: 0; font-size: 11px; font-weight: normal; } .search-view .messages { margin-top: -5px; cursor: default; } .search-view .message { padding-left: 22px; padding-right: 22px; padding-top: 0px; } .search-view .message p:first-child { margin-top: 0px; margin-bottom: 0px; padding-bottom: 4px; user-select: text; } .search-view > .results > .monaco-tree .sub-content { overflow: hidden; } .search-view .foldermatch, .search-view .filematch { display: flex; position: relative; line-height: 22px; padding: 0; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .filematch .monaco-icon-label { flex: 1; } .search-view .foldermatch .directory, .search-view .filematch .directory { opacity: 0.7; font-size: 0.9em; margin-left: 0.8em; } .search-view .foldermatch .badge, .search-view .filematch .badge { margin-left: 10px; } .search-view .linematch { position: relative; line-height: 22px; display: flex; } .search-view .linematch > .match { flex: 1; overflow: hidden; text-overflow: ellipsis; } .search-view .linematch.changedOrRemoved { font-style: italic; } .search-view .query-clear { background: url("action-query-clear.svg") center center no-repeat; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar { line-height: 1em; display: none; padding: 0 0.8em 0 0.4em; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-item { margin: 0; } .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: 0; /* in order to support a11y with keyboard, we use width: 0 to hide the actions, which still allows to "Tab" into the actions */ display: block; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .monaco-action-bar, .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: inherit; display: block; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-label { margin-right: 0.2em; margin-top: 4px; background-repeat: no-repeat; width: 16px; height: 16px; } .search-view .action-remove { background: url("action-remove.svg") center center no-repeat; } .search-view .action-replace { background-image: url('replace.svg'); } .search-view .action-replace-all { background: url('replace-all.svg') center center no-repeat; } .hc-black .search-view .action-replace, .vs-dark .search-view .action-replace { background-image: url('replace-inverse.svg'); } .hc-black .search-view .action-replace-all, .vs-dark .search-view .action-replace-all { background: url('replace-all-inverse.svg') center center no-repeat; } .search-view .label { font-style: italic; } .search-view .monaco-count-badge { margin-right: 12px; } .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .linematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .linematch .monaco-count-badge { display: none; } .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove, .vs-dark .monaco-workbench .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove { background: url("action-remove-focus.svg") center center no-repeat; } .monaco-workbench .search-action.refresh { background: url('Refresh.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.refresh, .hc-black .monaco-workbench .search-action.refresh { background: url('Refresh_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.collapse { background: url('CollapseAll.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.collapse, .hc-black .monaco-workbench .search-action.collapse { background: url('CollapseAll_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.clear-search-results, .hc-black .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results-dark.svg') center center no-repeat; } .monaco-workbench .search-action.cancel-search { background: url('stop.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.cancel-search, .hc-black .monaco-workbench .search-action.cancel-search { background: url('stop-inverse.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern, .hc-black .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern-dark.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles, .hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings-dark.svg') center center no-repeat; } .search-view .replace.findInFileMatch { text-decoration: line-through; } .search-view .findInFileMatch, .search-view .replaceMatch { white-space: pre; } .hc-black .monaco-workbench .search-view .replaceMatch, .hc-black .monaco-workbench .search-view .findInFileMatch { background: none !important; box-sizing: border-box; } .monaco-workbench .search-view a.prominent { text-decoration: underline; } /* Theming */ .vs .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(0, 0, 0, 0.1) !important; } .vs-dark .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(255, 255, 255, 0.1) !important; } .vs .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed.svg'); } .vs .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded.svg'); } .vs-dark .search-view .query-clear { background: url("action-query-clear-dark.svg") center center no-repeat; } .vs-dark .search-view .action-remove, .hc-black .search-view .action-remove { background: url("action-remove-dark.svg") center center no-repeat; } .vs-dark .search-view .message { opacity: .5; } .vs-dark .search-view .foldermatch, .vs-dark .search-view .filematch { padding: 0; } .vs-dark .search-view .search-widget .toggle-replace-button.expand, .hc-black .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded-dark.svg'); } .vs-dark .search-view .search-widget .toggle-replace-button.collapse, .hc-black .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed-dark.svg'); } /* High Contrast Theming */ .hc-black .monaco-workbench .search-view .foldermatch, .hc-black .monaco-workbench .search-view .filematch, .hc-black .monaco-workbench .search-view .linematch { line-height: 20px; }
src/vs/workbench/parts/search/browser/media/searchview.css
1
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.9904416799545288, 0.023838743567466736, 0.00016449243412353098, 0.0001754749973770231, 0.15095818042755127 ]
{ "id": 1, "code_window": [ "\tmargin-left: 0.8em;\n", "}\n", "\n", ".search-view .foldermatch .badge,\n", ".search-view .filematch .badge {\n", "\tmargin-left: 10px;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ ".search-view.wide .foldermatch .badge,\n", ".search-view.wide .filematch .badge {\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "replace", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./viewCursors'; import { ViewPart } from 'vs/editor/browser/view/viewPart'; import { Position } from 'vs/editor/common/core/position'; import { IViewCursorRenderData, ViewCursor } from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { TimeoutTimer, IntervalTimer } from 'vs/base/common/async'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { editorCursorForeground, editorCursorBackground } from 'vs/editor/common/view/editorColorRegistry'; import { TextEditorCursorBlinkingStyle, TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions'; export class ViewCursors extends ViewPart { static BLINK_INTERVAL = 500; private _readOnly: boolean; private _cursorBlinking: TextEditorCursorBlinkingStyle; private _cursorStyle: TextEditorCursorStyle; private _selectionIsEmpty: boolean; private _isVisible: boolean; private _domNode: FastDomNode<HTMLElement>; private _startCursorBlinkAnimation: TimeoutTimer; private _cursorFlatBlinkInterval: IntervalTimer; private _blinkingEnabled: boolean; private _editorHasFocus: boolean; private _primaryCursor: ViewCursor; private _secondaryCursors: ViewCursor[]; private _renderData: IViewCursorRenderData[]; constructor(context: ViewContext) { super(context); this._readOnly = this._context.configuration.editor.readOnly; this._cursorBlinking = this._context.configuration.editor.viewInfo.cursorBlinking; this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; this._selectionIsEmpty = true; this._primaryCursor = new ViewCursor(this._context); this._secondaryCursors = []; this._renderData = []; this._domNode = createFastDomNode(document.createElement('div')); this._domNode.setAttribute('role', 'presentation'); this._domNode.setAttribute('aria-hidden', 'true'); this._updateDomClassName(); this._domNode.appendChild(this._primaryCursor.getDomNode()); this._startCursorBlinkAnimation = new TimeoutTimer(); this._cursorFlatBlinkInterval = new IntervalTimer(); this._blinkingEnabled = false; this._editorHasFocus = false; this._updateBlinking(); } public dispose(): void { super.dispose(); this._startCursorBlinkAnimation.dispose(); this._cursorFlatBlinkInterval.dispose(); } public getDomNode(): FastDomNode<HTMLElement> { return this._domNode; } // --- begin event handlers public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { if (e.readOnly) { this._readOnly = this._context.configuration.editor.readOnly; } if (e.viewInfo) { this._cursorBlinking = this._context.configuration.editor.viewInfo.cursorBlinking; this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; } this._primaryCursor.onConfigurationChanged(e); this._updateBlinking(); if (e.viewInfo) { this._updateDomClassName(); } for (let i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].onConfigurationChanged(e); } return true; } private _onCursorPositionChanged(position: Position, secondaryPositions: Position[]): void { this._primaryCursor.onCursorPositionChanged(position); this._updateBlinking(); if (this._secondaryCursors.length < secondaryPositions.length) { // Create new cursors let addCnt = secondaryPositions.length - this._secondaryCursors.length; for (let i = 0; i < addCnt; i++) { let newCursor = new ViewCursor(this._context); this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling); this._secondaryCursors.push(newCursor); } } else if (this._secondaryCursors.length > secondaryPositions.length) { // Remove some cursors let removeCnt = this._secondaryCursors.length - secondaryPositions.length; for (let i = 0; i < removeCnt; i++) { this._domNode.removeChild(this._secondaryCursors[0].getDomNode()); this._secondaryCursors.splice(0, 1); } } for (let i = 0; i < secondaryPositions.length; i++) { this._secondaryCursors[i].onCursorPositionChanged(secondaryPositions[i]); } } public onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean { let positions: Position[] = []; for (let i = 0, len = e.selections.length; i < len; i++) { positions[i] = e.selections[i].getPosition(); } this._onCursorPositionChanged(positions[0], positions.slice(1)); const selectionIsEmpty = e.selections[0].isEmpty(); if (this._selectionIsEmpty !== selectionIsEmpty) { this._selectionIsEmpty = selectionIsEmpty; this._updateDomClassName(); } return true; } public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean { // true for inline decorations that can end up relayouting text return true; } public onFlushed(e: viewEvents.ViewFlushedEvent): boolean { return true; } public onFocusChanged(e: viewEvents.ViewFocusChangedEvent): boolean { this._editorHasFocus = e.isFocused; this._updateBlinking(); return false; } public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean { return true; } public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean { return true; } public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean { return true; } public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean { return true; } public onTokensChanged(e: viewEvents.ViewTokensChangedEvent): boolean { let shouldRender = (position: Position) => { for (let i = 0, len = e.ranges.length; i < len; i++) { if (e.ranges[i].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i].toLineNumber) { return true; } } return false; }; if (shouldRender(this._primaryCursor.getPosition())) { return true; } for (let i = 0; i < this._secondaryCursors.length; i++) { if (shouldRender(this._secondaryCursors[i].getPosition())) { return true; } } return false; } public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean { return true; } // --- end event handlers // ---- blinking logic private _getCursorBlinking(): TextEditorCursorBlinkingStyle { if (!this._editorHasFocus) { return TextEditorCursorBlinkingStyle.Hidden; } if (this._readOnly) { return TextEditorCursorBlinkingStyle.Solid; } return this._cursorBlinking; } private _updateBlinking(): void { this._startCursorBlinkAnimation.cancel(); this._cursorFlatBlinkInterval.cancel(); let blinkingStyle = this._getCursorBlinking(); // hidden and solid are special as they involve no animations let isHidden = (blinkingStyle === TextEditorCursorBlinkingStyle.Hidden); let isSolid = (blinkingStyle === TextEditorCursorBlinkingStyle.Solid); if (isHidden) { this._hide(); } else { this._show(); } this._blinkingEnabled = false; this._updateDomClassName(); if (!isHidden && !isSolid) { if (blinkingStyle === TextEditorCursorBlinkingStyle.Blink) { // flat blinking is handled by JavaScript to save battery life due to Chromium step timing issue https://bugs.chromium.org/p/chromium/issues/detail?id=361587 this._cursorFlatBlinkInterval.cancelAndSet(() => { if (this._isVisible) { this._hide(); } else { this._show(); } }, ViewCursors.BLINK_INTERVAL); } else { this._startCursorBlinkAnimation.setIfNotSet(() => { this._blinkingEnabled = true; this._updateDomClassName(); }, ViewCursors.BLINK_INTERVAL); } } } // --- end blinking logic private _updateDomClassName(): void { this._domNode.setClassName(this._getClassName()); } private _getClassName(): string { let result = 'cursors-layer'; if (!this._selectionIsEmpty) { result += ' has-selection'; } switch (this._cursorStyle) { case TextEditorCursorStyle.Line: result += ' cursor-line-style'; break; case TextEditorCursorStyle.Block: result += ' cursor-block-style'; break; case TextEditorCursorStyle.Underline: result += ' cursor-underline-style'; break; case TextEditorCursorStyle.LineThin: result += ' cursor-line-thin-style'; break; case TextEditorCursorStyle.BlockOutline: result += ' cursor-block-outline-style'; break; case TextEditorCursorStyle.UnderlineThin: result += ' cursor-underline-thin-style'; break; default: result += ' cursor-line-style'; } if (this._blinkingEnabled) { switch (this._getCursorBlinking()) { case TextEditorCursorBlinkingStyle.Blink: result += ' cursor-blink'; break; case TextEditorCursorBlinkingStyle.Smooth: result += ' cursor-smooth'; break; case TextEditorCursorBlinkingStyle.Phase: result += ' cursor-phase'; break; case TextEditorCursorBlinkingStyle.Expand: result += ' cursor-expand'; break; case TextEditorCursorBlinkingStyle.Solid: result += ' cursor-solid'; break; default: result += ' cursor-solid'; } } else { result += ' cursor-solid'; } return result; } private _show(): void { this._primaryCursor.show(); for (let i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].show(); } this._isVisible = true; } private _hide(): void { this._primaryCursor.hide(); for (let i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].hide(); } this._isVisible = false; } // ---- IViewPart implementation public prepareRender(ctx: RenderingContext): void { this._primaryCursor.prepareRender(ctx); for (let i = 0, len = this._secondaryCursors.length; i < len; i++) { this._secondaryCursors[i].prepareRender(ctx); } } public render(ctx: RestrictedRenderingContext): void { let renderData: IViewCursorRenderData[] = [], renderDataLen = 0; const primaryRenderData = this._primaryCursor.render(ctx); if (primaryRenderData) { renderData[renderDataLen++] = primaryRenderData; } for (let i = 0, len = this._secondaryCursors.length; i < len; i++) { const secondaryRenderData = this._secondaryCursors[i].render(ctx); if (secondaryRenderData) { renderData[renderDataLen++] = secondaryRenderData; } } this._renderData = renderData; } public getLastRenderData(): IViewCursorRenderData[] { return this._renderData; } } registerThemingParticipant((theme, collector) => { let caret = theme.getColor(editorCursorForeground); if (caret) { let caretBackground = theme.getColor(editorCursorBackground); if (!caretBackground) { caretBackground = caret.opposite(); } collector.addRule(`.monaco-editor .cursor { background-color: ${caret}; border-color: ${caret}; color: ${caretBackground}; }`); if (theme.type === 'hc') { collector.addRule(`.monaco-editor .cursors-layer.has-selection .cursor { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`); } } });
src/vs/editor/browser/viewParts/viewCursors/viewCursors.ts
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.0001748468348523602, 0.00016878343012649566, 0.00016383265028707683, 0.0001685262395767495, 0.0000027445605610409984 ]
{ "id": 1, "code_window": [ "\tmargin-left: 0.8em;\n", "}\n", "\n", ".search-view .foldermatch .badge,\n", ".search-view .filematch .badge {\n", "\tmargin-left: 10px;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ ".search-view.wide .foldermatch .badge,\n", ".search-view.wide .filematch .badge {\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "replace", "edit_start_line_idx": 195 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "quickOpen.terminal": "Показать все открытые терминалы", "terminal": "Терминал", "terminalIntegratedConfigurationTitle": "Интегрированный терминал", "terminal.integrated.shell.linux": "Путь оболочки, который используется терминалом в Linux.", "terminal.integrated.shellArgs.linux": "Аргументы командной строки, которые следует использовать в терминале Linux.", "terminal.integrated.shell.osx": "Путь оболочки, который используется терминалом в OS X.", "terminal.integrated.shellArgs.osx": "Аргументы командной строки, которые следует использовать в терминале OS X.", "terminal.integrated.shell.windows": "Путь к оболочке, который используется терминалом в Windows. Для оболочек, входящих в состав ОС Windows (cmd, PowerShell или Bash в Ubuntu).", "terminal.integrated.shellArgs.windows": "Аргументы командной строки, используемые в терминале Windows.", "terminal.integrated.macOptionIsMeta": "Считать клавишу OPTION метаклавишей в терминале macOS.", "terminal.integrated.copyOnSelection": "Если задано, текст выделенный в терминале будет скопирован в буфер обмена", "terminal.integrated.fontFamily": "Определяет семейство шрифтов терминала, значение по умолчанию — editor.fontFamily.", "terminal.integrated.fontSize": "Определяет размер шрифта (в пикселях) для терминала.", "terminal.integrated.lineHeight": "Определяет высоту строки терминала; это число умножается на размер шрифта терминала, что дает фактическую высоту строки в пикселях.", "terminal.integrated.fontWeight": "Размер шрифта в терминале для нежирного текста.", "terminal.integrated.fontWeightBold": "Размер шрифта в терминале для полужирного текста. ", "terminal.integrated.cursorBlinking": "Управляет миганием курсора терминала.", "terminal.integrated.cursorStyle": "Определяет стиль курсора терминала.", "terminal.integrated.scrollback": "Определяет предельное число строк в буфере терминала.", "terminal.integrated.setLocaleVariables": "Управляет заданием переменных при запуске терминала, значение по умолчанию: \"True\" для OS X и \"False\" для других платформ.", "terminal.integrated.rightClickBehavior": "Управляет тем, как терминал реагирует на щелчок правой кнопкой мыши. Возможные значения: 'default', 'copyPaste' и 'selectWord'. При выборе варианта 'default' будет показано контекстное меню, при выборе варианта 'copyPaste' выделенный текст будет скопирован, а при отсутствии выделенного текста - вставлен, при выборе варианта 'selectWord' будет выбрано слово, над которым находится курсор, и показано контекстное меню.", "terminal.integrated.cwd": "Путь явного запуска, по которому будет запущен терминал. Используется в качестве текущего рабочего каталога (cwd) для процесса оболочки. Это может быть особенно удобно в параметрах рабочей области, если корневой каталог не является подходящим каталогом cwd.", "terminal.integrated.confirmOnExit": "Указывает, следует ли при выходе выводить подтверждение об имеющихся активных сеансах терминала.", "terminal.integrated.enableBell": "Определяет, включен ли \"звонок\" терминала.", "terminal.integrated.commandsToSkipShell": "Набор идентификаторов команд, настраиваемые сочетания клавиш которых не будут передаваться в оболочку, а вместо этого будут всегда обрабатываться Code. Это позволяет использовать настраиваемые сочетания клавиш, которые при обычных условиях были бы использованы оболочкой и работали бы так же, как если бы терминал не имел фокуса, например клавиши CTRL+P запускали бы Quick Open.", "terminal.integrated.env.osx": "Объект с переменными среды, которые будут добавлены к процессу VS Code для использования в терминале OS X", "terminal.integrated.env.linux": "Объект с переменными среды, которые будут добавлены к процессу VS Code для использования в терминале Linux ", "terminal.integrated.env.windows": "Объект с переменными среды, которые будут добавлены к процессу VS Code для использования в терминале Windows", "terminal.integrated.showExitAlert": "Отображать предупреждение \"Процесс терминала завершен с кодом выхода\", если код выхода не равен нулю.", "terminal.integrated.experimentalRestore": "Восстанавливать ли сеансы терминала для рабочей области автоматически при запуске VS Code. Это экспериментальный параметр; он может приводить к ошибкам и может быть изменен в будущем.", "terminalCategory": "Терминал", "viewCategory": "Просмотреть" }
i18n/rus/src/vs/workbench/parts/terminal/electron-browser/terminal.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.007888028398156166, 0.0025165921542793512, 0.00017134821973741055, 0.0011255730642005801, 0.0029076593928039074 ]
{ "id": 1, "code_window": [ "\tmargin-left: 0.8em;\n", "}\n", "\n", ".search-view .foldermatch .badge,\n", ".search-view .filematch .badge {\n", "\tmargin-left: 10px;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ ".search-view.wide .foldermatch .badge,\n", ".search-view.wide .filematch .badge {\n" ], "file_path": "src/vs/workbench/parts/search/browser/media/searchview.css", "type": "replace", "edit_start_line_idx": 195 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "labelLoading": "로드 중..." }
i18n/kor/src/vs/editor/contrib/referenceSearch/browser/referencesController.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017484650015830994, 0.00017484650015830994, 0.00017484650015830994, 0.00017484650015830994, 0 ]
{ "id": 2, "code_window": [ "export class SearchView extends Viewlet implements IViewlet, IPanel {\n", "\n", "\tprivate static readonly MAX_TEXT_RESULTS = 10000;\n", "\tprivate static readonly SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';\n", "\n", "\tprivate isDisposed: boolean;\n", "\n", "\tprivate queryBuilder: QueryBuilder;\n", "\tprivate viewModel: SearchModel;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static readonly WIDE_CLASS_NAME = 'wide';\n", "\tprivate static readonly WIDE_VIEW_SIZE = 600;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .vs .panel .search-view .monaco-inputbox { border: 1px solid #ddd; } .search-view .search-widgets-container { margin: 0px 9px 0 2px; padding-top: 6px; } .search-view .search-widget .toggle-replace-button { position: absolute; top: 0; left: 0; width: 16px; height: 100%; box-sizing: border-box; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .search-view .search-widget .search-container, .search-view .search-widget .replace-container { margin-left: 17px; } .search-view .search-widget .input-box, .search-view .search-widget .input-box .monaco-inputbox { height: 25px; } .search-view .search-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .search-view .search-widget .replace-container { margin-top: 6px; position: relative; display: inline-flex; } .search-view .search-widget .replace-container.disabled { display: none; } .search-view .search-widget .replace-container .monaco-action-bar { margin-left: 3px; } .search-view .search-widget .replace-container .monaco-action-bar { height: 25px; } .search-view .search-widget .replace-container .monaco-action-bar .action-item .icon { background-repeat: no-repeat; width: 20px; height: 25px; } .search-view .query-clear { width: 20px; height: 20px; position: absolute; top: 3px; right: 3px; cursor: pointer; } .search-view .query-details { min-height: 1em; position: relative; margin: 0 0 0 17px; } .search-view .query-details .more { position: absolute; margin-right: 0.3em; right: 0; cursor: pointer; width: 16px; height: 13px; z-index: 2; /* Force it above the search results message, which has a negative top margin */ } .hc-black .monaco-workbench .search-view .query-details .more, .vs-dark .monaco-workbench .search-view .query-details .more { background: url('ellipsis-inverse.svg') top center no-repeat; } .vs .monaco-workbench .search-view .query-details .more { background: url('ellipsis.svg') top center no-repeat; } .search-view .query-details .file-types { display: none; } .search-view .query-details .file-types > .monaco-inputbox { width: 100%; height: 25px; } .search-view .query-details.more .file-types { display: inherit; } .search-view .query-details.more .file-types:last-child { padding-bottom: 10px; } .search-view .query-details .search-pattern-info { width: 16px; height: 16px; } .search-view .query-details .search-configure-exclusions { width: 16px; height: 16px; } .monaco-action-bar .action-label.search-configure-exclusions { margin-right: 2px; } .vs-dark .monaco-workbench .search-configure-exclusions, .hc-black .monaco-workbench .search-configure-exclusions { background: url('configure-inverse.svg') center center no-repeat; opacity: .7; } .vs .monaco-workbench .search-configure-exclusions { background: url('configure.svg') center center no-repeat; opacity: 0.7; } .search-view .query-details.more h4 { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; padding: 4px 0 0; margin: 0; font-size: 11px; font-weight: normal; } .search-view .messages { margin-top: -5px; cursor: default; } .search-view .message { padding-left: 22px; padding-right: 22px; padding-top: 0px; } .search-view .message p:first-child { margin-top: 0px; margin-bottom: 0px; padding-bottom: 4px; user-select: text; } .search-view > .results > .monaco-tree .sub-content { overflow: hidden; } .search-view .foldermatch, .search-view .filematch { display: flex; position: relative; line-height: 22px; padding: 0; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .filematch .monaco-icon-label { flex: 1; } .search-view .foldermatch .directory, .search-view .filematch .directory { opacity: 0.7; font-size: 0.9em; margin-left: 0.8em; } .search-view .foldermatch .badge, .search-view .filematch .badge { margin-left: 10px; } .search-view .linematch { position: relative; line-height: 22px; display: flex; } .search-view .linematch > .match { flex: 1; overflow: hidden; text-overflow: ellipsis; } .search-view .linematch.changedOrRemoved { font-style: italic; } .search-view .query-clear { background: url("action-query-clear.svg") center center no-repeat; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar { line-height: 1em; display: none; padding: 0 0.8em 0 0.4em; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-item { margin: 0; } .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: 0; /* in order to support a11y with keyboard, we use width: 0 to hide the actions, which still allows to "Tab" into the actions */ display: block; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .monaco-action-bar, .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: inherit; display: block; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-label { margin-right: 0.2em; margin-top: 4px; background-repeat: no-repeat; width: 16px; height: 16px; } .search-view .action-remove { background: url("action-remove.svg") center center no-repeat; } .search-view .action-replace { background-image: url('replace.svg'); } .search-view .action-replace-all { background: url('replace-all.svg') center center no-repeat; } .hc-black .search-view .action-replace, .vs-dark .search-view .action-replace { background-image: url('replace-inverse.svg'); } .hc-black .search-view .action-replace-all, .vs-dark .search-view .action-replace-all { background: url('replace-all-inverse.svg') center center no-repeat; } .search-view .label { font-style: italic; } .search-view .monaco-count-badge { margin-right: 12px; } .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .linematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .linematch .monaco-count-badge { display: none; } .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove, .vs-dark .monaco-workbench .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove { background: url("action-remove-focus.svg") center center no-repeat; } .monaco-workbench .search-action.refresh { background: url('Refresh.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.refresh, .hc-black .monaco-workbench .search-action.refresh { background: url('Refresh_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.collapse { background: url('CollapseAll.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.collapse, .hc-black .monaco-workbench .search-action.collapse { background: url('CollapseAll_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.clear-search-results, .hc-black .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results-dark.svg') center center no-repeat; } .monaco-workbench .search-action.cancel-search { background: url('stop.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.cancel-search, .hc-black .monaco-workbench .search-action.cancel-search { background: url('stop-inverse.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern, .hc-black .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern-dark.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles, .hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings-dark.svg') center center no-repeat; } .search-view .replace.findInFileMatch { text-decoration: line-through; } .search-view .findInFileMatch, .search-view .replaceMatch { white-space: pre; } .hc-black .monaco-workbench .search-view .replaceMatch, .hc-black .monaco-workbench .search-view .findInFileMatch { background: none !important; box-sizing: border-box; } .monaco-workbench .search-view a.prominent { text-decoration: underline; } /* Theming */ .vs .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(0, 0, 0, 0.1) !important; } .vs-dark .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(255, 255, 255, 0.1) !important; } .vs .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed.svg'); } .vs .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded.svg'); } .vs-dark .search-view .query-clear { background: url("action-query-clear-dark.svg") center center no-repeat; } .vs-dark .search-view .action-remove, .hc-black .search-view .action-remove { background: url("action-remove-dark.svg") center center no-repeat; } .vs-dark .search-view .message { opacity: .5; } .vs-dark .search-view .foldermatch, .vs-dark .search-view .filematch { padding: 0; } .vs-dark .search-view .search-widget .toggle-replace-button.expand, .hc-black .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded-dark.svg'); } .vs-dark .search-view .search-widget .toggle-replace-button.collapse, .hc-black .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed-dark.svg'); } /* High Contrast Theming */ .hc-black .monaco-workbench .search-view .foldermatch, .hc-black .monaco-workbench .search-view .filematch, .hc-black .monaco-workbench .search-view .linematch { line-height: 20px; }
src/vs/workbench/parts/search/browser/media/searchview.css
1
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017513566126581281, 0.0001700596185401082, 0.000164204859174788, 0.0001698538544587791, 0.0000024795626814011484 ]
{ "id": 2, "code_window": [ "export class SearchView extends Viewlet implements IViewlet, IPanel {\n", "\n", "\tprivate static readonly MAX_TEXT_RESULTS = 10000;\n", "\tprivate static readonly SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';\n", "\n", "\tprivate isDisposed: boolean;\n", "\n", "\tprivate queryBuilder: QueryBuilder;\n", "\tprivate viewModel: SearchModel;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static readonly WIDE_CLASS_NAME = 'wide';\n", "\tprivate static readonly WIDE_VIEW_SIZE = 600;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!../browser/media/breakpointWidget'; import * as nls from 'vs/nls'; import * as errors from 'vs/base/common/errors'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; import { Position } from 'vs/editor/common/core/position'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ZoneWidget } from 'vs/editor/contrib/zoneWidget/zoneWidget'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDebugService, IBreakpoint, BreakpointWidgetContext as Context, CONTEXT_BREAKPOINT_WIDGET_VISIBLE, DEBUG_SCHEME, IDebugEditorContribution, EDITOR_CONTRIBUTION_ID } from 'vs/workbench/parts/debug/common/debug'; import { attachSelectBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { SimpleDebugEditor } from 'vs/workbench/parts/debug/electron-browser/simpleDebugEditor'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { IModelService } from 'vs/editor/common/services/modelService'; import uri from 'vs/base/common/uri'; import { SuggestRegistry, ISuggestResult, SuggestContext, SuggestTriggerKind } from 'vs/editor/common/modes'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ITextModel } from 'vs/editor/common/model'; import { wireCancellationToken } from 'vs/base/common/async'; import { provideSuggestionItems } from 'vs/editor/contrib/suggest/suggest'; import { TPromise } from 'vs/base/common/winjs.base'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { transparent, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IDecorationOptions } from 'vs/editor/common/editorCommon'; const $ = dom.$; const IPrivateBreakopintWidgetService = createDecorator<IPrivateBreakopintWidgetService>('privateBreakopintWidgetService'); export interface IPrivateBreakopintWidgetService { _serviceBrand: any; close(success: boolean): void; } const DECORATION_KEY = 'breakpointwidgetdecoration'; export class BreakpointWidget extends ZoneWidget implements IPrivateBreakopintWidgetService { public _serviceBrand: any; private selectContainer: HTMLElement; private input: SimpleDebugEditor; private toDispose: lifecycle.IDisposable[]; private conditionInput = ''; private hitCountInput = ''; private logMessageInput = ''; private breakpoint: IBreakpoint; constructor(editor: ICodeEditor, private lineNumber: number, private column: number, private context: Context, @IContextViewService private contextViewService: IContextViewService, @IDebugService private debugService: IDebugService, @IThemeService private themeService: IThemeService, @IContextKeyService private contextKeyService: IContextKeyService, @IInstantiationService private instantiationService: IInstantiationService, @IModelService private modelService: IModelService, @ICodeEditorService private codeEditorService: ICodeEditorService, ) { super(editor, { showFrame: true, showArrow: false, frameWidth: 1 }); this.toDispose = []; const uri = this.editor.getModel().uri; this.breakpoint = this.debugService.getModel().getBreakpoints().filter(bp => bp.lineNumber === this.lineNumber && bp.column === this.column && bp.uri.toString() === uri.toString()).pop(); if (this.context === undefined) { if (this.breakpoint && !this.breakpoint.condition && !this.breakpoint.hitCondition && this.breakpoint.logMessage) { this.context = Context.LOG_MESSAGE; } else if (this.breakpoint && !this.breakpoint.condition && this.breakpoint.hitCondition) { this.context = Context.HIT_COUNT; } else { this.context = Context.CONDITION; } } this.toDispose.push(this.debugService.getModel().onDidChangeBreakpoints(e => { if (this.breakpoint && e.removed && e.removed.indexOf(this.breakpoint) >= 0) { this.dispose(); } })); this.codeEditorService.registerDecorationType(DECORATION_KEY, {}); this.create(); } private get placeholder(): string { switch (this.context) { case Context.LOG_MESSAGE: return nls.localize('breakpointWidgetLogMessagePlaceholder', "Message to log when breakpoint is hit. Expressions within {} are interpolated. 'Enter' to accept, 'esc' to cancel."); case Context.HIT_COUNT: return nls.localize('breakpointWidgetHitCountPlaceholder', "Break when hit count condition is met. 'Enter' to accept, 'esc' to cancel."); default: return nls.localize('breakpointWidgetExpressionPlaceholder', "Break when expression evaluates to true. 'Enter' to accept, 'esc' to cancel."); } } private getInputValue(breakpoint: IBreakpoint): string { switch (this.context) { case Context.LOG_MESSAGE: return breakpoint && breakpoint.logMessage ? breakpoint.logMessage : this.logMessageInput; case Context.HIT_COUNT: return breakpoint && breakpoint.hitCondition ? breakpoint.hitCondition : this.hitCountInput; default: return breakpoint && breakpoint.condition ? breakpoint.condition : this.conditionInput; } } private rememberInput(): void { const value = this.input.getModel().getValue(); switch (this.context) { case Context.LOG_MESSAGE: this.logMessageInput = value; break; case Context.HIT_COUNT: this.hitCountInput = value; break; default: this.conditionInput = value; } } protected _fillContainer(container: HTMLElement): void { this.setCssClass('breakpoint-widget'); const selectBox = new SelectBox([nls.localize('expression', "Expression"), nls.localize('hitCount', "Hit Count"), nls.localize('logMessage', "Log Message")], this.context, this.contextViewService); this.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService)); this.selectContainer = $('.breakpoint-select-container'); selectBox.render(dom.append(container, this.selectContainer)); selectBox.onDidSelect(e => { this.rememberInput(); this.context = e.index; const value = this.getInputValue(this.breakpoint); this.input.getModel().setValue(value); }); this.createBreakpointInput(dom.append(container, $('.inputContainer'))); this.input.getModel().setValue(this.getInputValue(this.breakpoint)); // Due to an electron bug we have to do the timeout, otherwise we do not get focus setTimeout(() => this.input.focus(), 70); } public close(success: boolean): void { if (success) { // if there is already a breakpoint on this location - remove it. let condition = this.breakpoint && this.breakpoint.condition; let hitCondition = this.breakpoint && this.breakpoint.hitCondition; let logMessage = this.breakpoint && this.breakpoint.logMessage; this.rememberInput(); if (this.conditionInput) { condition = this.conditionInput; } if (this.hitCountInput) { hitCondition = this.hitCountInput; } if (this.logMessageInput) { logMessage = this.logMessageInput; } if (this.breakpoint) { this.debugService.updateBreakpoints(this.breakpoint.uri, { [this.breakpoint.getId()]: { condition, hitCondition, verified: this.breakpoint.verified, logMessage } }, false); } else { this.debugService.addBreakpoints(this.editor.getModel().uri, [{ lineNumber: this.lineNumber, column: this.breakpoint ? this.breakpoint.column : undefined, enabled: true, condition, hitCondition, logMessage }]).done(null, errors.onUnexpectedError); } } this.dispose(); } protected _doLayout(heightInPixel: number, widthInPixel: number): void { this.input.layout({ height: 18, width: widthInPixel - 113 }); } private createBreakpointInput(container: HTMLElement): void { const scopedContextKeyService = this.contextKeyService.createScoped(container); this.toDispose.push(scopedContextKeyService); const scopedInstatiationService = this.instantiationService.createChild(new ServiceCollection( [IContextKeyService, scopedContextKeyService], [IPrivateBreakopintWidgetService, this])); const options = SimpleDebugEditor.getEditorOptions(); this.input = scopedInstatiationService.createInstance(SimpleDebugEditor, container, options); const model = this.modelService.createModel('', null, uri.parse(`${DEBUG_SCHEME}:breakpointinput`), true); this.input.setModel(model); this.toDispose.push(model); const setDecorations = () => { const value = this.input.getModel().getValue(); const decorations = !!value ? [] : this.createDecorations(); this.input.setDecorations(DECORATION_KEY, decorations); }; this.input.getModel().onDidChangeContent(() => setDecorations()); this.themeService.onThemeChange(() => setDecorations()); this.toDispose.push(SuggestRegistry.register({ scheme: DEBUG_SCHEME, hasAccessToAllModels: true }, { triggerCharacters: ['.'], provideCompletionItems: (model: ITextModel, position: Position, _context: SuggestContext, token: CancellationToken): Thenable<ISuggestResult> => { let suggestions: TPromise<ISuggestResult>; if (this.context === Context.CONDITION || this.context === Context.LOG_MESSAGE && this.isCurlyBracketOpen()) { suggestions = provideSuggestionItems(this.editor.getModel(), this.editor.getPosition(), 'none', undefined, { triggerKind: SuggestTriggerKind.Invoke }).then(suggestions => { return { suggestions: suggestions.map(s => s.suggestion) }; }); } else { suggestions = TPromise.as({ suggestions: [] }); } return wireCancellationToken(token, suggestions); } })); } private createDecorations(): IDecorationOptions[] { return [{ range: { startLineNumber: 0, endLineNumber: 0, startColumn: 0, endColumn: 1 }, renderOptions: { after: { contentText: this.placeholder, color: transparent(editorForeground, 0.4)(this.themeService.getTheme()).toString() } } }]; } private isCurlyBracketOpen(): boolean { const value = this.input.getModel().getValue(); for (let i = this.input.getPosition().column - 2; i >= 0; i--) { if (value[i] === '{') { return true; } if (value[i] === '}') { return false; } } return false; } public dispose(): void { super.dispose(); this.input.dispose(); lifecycle.dispose(this.toDispose); setTimeout(() => this.editor.focus(), 0); } } class AcceptBreakpointWidgetInputAction extends EditorCommand { constructor() { super({ id: 'breakpointWidget.action.acceptInput', precondition: CONTEXT_BREAKPOINT_WIDGET_VISIBLE, // TODO@Isidor need a more specific context key if breakpoint widget is focused kbOpts: { kbExpr: EditorContextKeys.textInputFocus, primary: KeyCode.Enter } }); } public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { accessor.get(IPrivateBreakopintWidgetService).close(true); } } class CloseBreakpointWidgetCommand extends EditorCommand { constructor() { super({ id: 'closeBreakpointWidget', precondition: CONTEXT_BREAKPOINT_WIDGET_VISIBLE, kbOpts: { kbExpr: EditorContextKeys.textInputFocus, primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] } }); } public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void { const debugContribution = editor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID); if (debugContribution) { // if focus is in outer editor we need to use the debug contribution to close return debugContribution.closeBreakpointWidget(); } accessor.get(IPrivateBreakopintWidgetService).close(false); } } registerEditorCommand(new AcceptBreakpointWidgetInputAction()); registerEditorCommand(new CloseBreakpointWidgetCommand());
src/vs/workbench/parts/debug/electron-browser/breakpointWidget.ts
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00023642035375814885, 0.00017509216559119523, 0.00016618291556369513, 0.0001710767683107406, 0.000014532161912939046 ]
{ "id": 2, "code_window": [ "export class SearchView extends Viewlet implements IViewlet, IPanel {\n", "\n", "\tprivate static readonly MAX_TEXT_RESULTS = 10000;\n", "\tprivate static readonly SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';\n", "\n", "\tprivate isDisposed: boolean;\n", "\n", "\tprivate queryBuilder: QueryBuilder;\n", "\tprivate viewModel: SearchModel;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static readonly WIDE_CLASS_NAME = 'wide';\n", "\tprivate static readonly WIDE_VIEW_SIZE = 600;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 71 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "YAML Dil Temelleri", "description": "YAML dosyaları için söz dizimi vurgulama ve ayraç eşleştirme sağlar." }
i18n/trk/extensions/yaml/package.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.0001782245672075078, 0.00017741427291184664, 0.00017660396406427026, 0.00017741427291184664, 8.103015716187656e-7 ]
{ "id": 2, "code_window": [ "export class SearchView extends Viewlet implements IViewlet, IPanel {\n", "\n", "\tprivate static readonly MAX_TEXT_RESULTS = 10000;\n", "\tprivate static readonly SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';\n", "\n", "\tprivate isDisposed: boolean;\n", "\n", "\tprivate queryBuilder: QueryBuilder;\n", "\tprivate viewModel: SearchModel;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate static readonly WIDE_CLASS_NAME = 'wide';\n", "\tprivate static readonly WIDE_VIEW_SIZE = 600;\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 71 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "treeView.notRegistered": "Kayıtlı '{0}' Id'li ağaç görünümü yok.", "treeView.duplicateElement": "{0} kimliğine sahip bir öge zaten kayıtlı" }
i18n/trk/src/vs/workbench/api/node/extHostTreeViews.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017660396406427026, 0.00017622523591853678, 0.00017584649322088808, 0.00017622523591853678, 3.7873542169108987e-7 ]
{ "id": 3, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis.searchWidget.setWidth(this.size.width - 28 /* container margin */);\n", "\n", "\t\tthis.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.size.width >= SearchView.WIDE_VIEW_SIZE) {\n", "\t\t\tthis.getContainer().addClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t} else {\n", "\t\t\tthis.getContainer().removeClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 750 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .vs .panel .search-view .monaco-inputbox { border: 1px solid #ddd; } .search-view .search-widgets-container { margin: 0px 9px 0 2px; padding-top: 6px; } .search-view .search-widget .toggle-replace-button { position: absolute; top: 0; left: 0; width: 16px; height: 100%; box-sizing: border-box; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .search-view .search-widget .search-container, .search-view .search-widget .replace-container { margin-left: 17px; } .search-view .search-widget .input-box, .search-view .search-widget .input-box .monaco-inputbox { height: 25px; } .search-view .search-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .search-view .search-widget .replace-container { margin-top: 6px; position: relative; display: inline-flex; } .search-view .search-widget .replace-container.disabled { display: none; } .search-view .search-widget .replace-container .monaco-action-bar { margin-left: 3px; } .search-view .search-widget .replace-container .monaco-action-bar { height: 25px; } .search-view .search-widget .replace-container .monaco-action-bar .action-item .icon { background-repeat: no-repeat; width: 20px; height: 25px; } .search-view .query-clear { width: 20px; height: 20px; position: absolute; top: 3px; right: 3px; cursor: pointer; } .search-view .query-details { min-height: 1em; position: relative; margin: 0 0 0 17px; } .search-view .query-details .more { position: absolute; margin-right: 0.3em; right: 0; cursor: pointer; width: 16px; height: 13px; z-index: 2; /* Force it above the search results message, which has a negative top margin */ } .hc-black .monaco-workbench .search-view .query-details .more, .vs-dark .monaco-workbench .search-view .query-details .more { background: url('ellipsis-inverse.svg') top center no-repeat; } .vs .monaco-workbench .search-view .query-details .more { background: url('ellipsis.svg') top center no-repeat; } .search-view .query-details .file-types { display: none; } .search-view .query-details .file-types > .monaco-inputbox { width: 100%; height: 25px; } .search-view .query-details.more .file-types { display: inherit; } .search-view .query-details.more .file-types:last-child { padding-bottom: 10px; } .search-view .query-details .search-pattern-info { width: 16px; height: 16px; } .search-view .query-details .search-configure-exclusions { width: 16px; height: 16px; } .monaco-action-bar .action-label.search-configure-exclusions { margin-right: 2px; } .vs-dark .monaco-workbench .search-configure-exclusions, .hc-black .monaco-workbench .search-configure-exclusions { background: url('configure-inverse.svg') center center no-repeat; opacity: .7; } .vs .monaco-workbench .search-configure-exclusions { background: url('configure.svg') center center no-repeat; opacity: 0.7; } .search-view .query-details.more h4 { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; padding: 4px 0 0; margin: 0; font-size: 11px; font-weight: normal; } .search-view .messages { margin-top: -5px; cursor: default; } .search-view .message { padding-left: 22px; padding-right: 22px; padding-top: 0px; } .search-view .message p:first-child { margin-top: 0px; margin-bottom: 0px; padding-bottom: 4px; user-select: text; } .search-view > .results > .monaco-tree .sub-content { overflow: hidden; } .search-view .foldermatch, .search-view .filematch { display: flex; position: relative; line-height: 22px; padding: 0; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .foldermatch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .filematch .monaco-icon-label, .search-view .monaco-tree .monaco-tree-row.focused .filematch .monaco-icon-label { flex: 1; } .search-view .foldermatch .directory, .search-view .filematch .directory { opacity: 0.7; font-size: 0.9em; margin-left: 0.8em; } .search-view .foldermatch .badge, .search-view .filematch .badge { margin-left: 10px; } .search-view .linematch { position: relative; line-height: 22px; display: flex; } .search-view .linematch > .match { flex: 1; overflow: hidden; text-overflow: ellipsis; } .search-view .linematch.changedOrRemoved { font-style: italic; } .search-view .query-clear { background: url("action-query-clear.svg") center center no-repeat; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar { line-height: 1em; display: none; padding: 0 0.8em 0 0.4em; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-item { margin: 0; } .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: 0; /* in order to support a11y with keyboard, we use width: 0 to hide the actions, which still allows to "Tab" into the actions */ display: block; } .search-view .monaco-tree .monaco-tree-row:hover:not(.highlighted) .monaco-action-bar, .search-view .monaco-tree .monaco-tree-row.focused .monaco-action-bar { width: inherit; display: block; } .search-view .monaco-tree .monaco-tree-row .monaco-action-bar .action-label { margin-right: 0.2em; margin-top: 4px; background-repeat: no-repeat; width: 16px; height: 16px; } .search-view .action-remove { background: url("action-remove.svg") center center no-repeat; } .search-view .action-replace { background-image: url('replace.svg'); } .search-view .action-replace-all { background: url('replace-all.svg') center center no-repeat; } .hc-black .search-view .action-replace, .vs-dark .search-view .action-replace { background-image: url('replace-inverse.svg'); } .hc-black .search-view .action-replace-all, .vs-dark .search-view .action-replace-all { background: url('replace-all-inverse.svg') center center no-repeat; } .search-view .label { font-style: italic; } .search-view .monaco-count-badge { margin-right: 12px; } .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree .monaco-tree-row:hover .content .linematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .filematch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .foldermatch .monaco-count-badge, .search-view > .results > .monaco-tree.focused .monaco-tree-row.focused .content .linematch .monaco-count-badge { display: none; } .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove, .vs-dark .monaco-workbench .search-view .focused .monaco-tree-row.selected:not(.highlighted) > .content.actions .action-remove { background: url("action-remove-focus.svg") center center no-repeat; } .monaco-workbench .search-action.refresh { background: url('Refresh.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.refresh, .hc-black .monaco-workbench .search-action.refresh { background: url('Refresh_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.collapse { background: url('CollapseAll.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.collapse, .hc-black .monaco-workbench .search-action.collapse { background: url('CollapseAll_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.clear-search-results, .hc-black .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results-dark.svg') center center no-repeat; } .monaco-workbench .search-action.cancel-search { background: url('stop.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.cancel-search, .hc-black .monaco-workbench .search-action.cancel-search { background: url('stop-inverse.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern, .hc-black .monaco-workbench .search-view .query-details .file-types .controls > .monaco-custom-checkbox.pattern { background: url('pattern-dark.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles, .hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings-dark.svg') center center no-repeat; } .search-view .replace.findInFileMatch { text-decoration: line-through; } .search-view .findInFileMatch, .search-view .replaceMatch { white-space: pre; } .hc-black .monaco-workbench .search-view .replaceMatch, .hc-black .monaco-workbench .search-view .findInFileMatch { background: none !important; box-sizing: border-box; } .monaco-workbench .search-view a.prominent { text-decoration: underline; } /* Theming */ .vs .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(0, 0, 0, 0.1) !important; } .vs-dark .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(255, 255, 255, 0.1) !important; } .vs .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed.svg'); } .vs .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded.svg'); } .vs-dark .search-view .query-clear { background: url("action-query-clear-dark.svg") center center no-repeat; } .vs-dark .search-view .action-remove, .hc-black .search-view .action-remove { background: url("action-remove-dark.svg") center center no-repeat; } .vs-dark .search-view .message { opacity: .5; } .vs-dark .search-view .foldermatch, .vs-dark .search-view .filematch { padding: 0; } .vs-dark .search-view .search-widget .toggle-replace-button.expand, .hc-black .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded-dark.svg'); } .vs-dark .search-view .search-widget .toggle-replace-button.collapse, .hc-black .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed-dark.svg'); } /* High Contrast Theming */ .hc-black .monaco-workbench .search-view .foldermatch, .hc-black .monaco-workbench .search-view .filematch, .hc-black .monaco-workbench .search-view .linematch { line-height: 20px; }
src/vs/workbench/parts/search/browser/media/searchview.css
1
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017501898400951177, 0.00016924050578381866, 0.0001642665738472715, 0.00016960850916802883, 0.0000025885735794872744 ]
{ "id": 3, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis.searchWidget.setWidth(this.size.width - 28 /* container margin */);\n", "\n", "\t\tthis.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.size.width >= SearchView.WIDE_VIEW_SIZE) {\n", "\t\t\tthis.getContainer().addClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t} else {\n", "\t\t\tthis.getContainer().removeClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 750 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "action.showContextMenu.label": "Düzenleyici Bağlam Menüsünü Göster" }
i18n/trk/src/vs/editor/contrib/contextmenu/contextmenu.i18n.json
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.0001777205616235733, 0.00017681035387795419, 0.00017590014613233507, 0.00017681035387795419, 9.102077456191182e-7 ]
{ "id": 3, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis.searchWidget.setWidth(this.size.width - 28 /* container margin */);\n", "\n", "\t\tthis.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.size.width >= SearchView.WIDE_VIEW_SIZE) {\n", "\t\t\tthis.getContainer().addClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t} else {\n", "\t\t\tthis.getContainer().removeClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 750 }
/*--------------------------------------------------------------------------------------------- * 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 { IModelDecorationOptions } from 'vs/editor/common/model'; import { IDecorationRenderOptions } from 'vs/editor/common/editorCommon'; import { AbstractCodeEditorService } from 'vs/editor/browser/services/abstractCodeEditorService'; export class TestCodeEditorService extends AbstractCodeEditorService { public registerDecorationType(key: string, options: IDecorationRenderOptions, parentTypeKey?: string): void { } public removeDecorationType(key: string): void { } public resolveDecorationOptions(decorationTypeKey: string, writable: boolean): IModelDecorationOptions { return null; } }
src/vs/editor/test/browser/testCodeEditorService.ts
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017599930288270116, 0.00017156737158074975, 0.0001671354257268831, 0.00017156737158074975, 0.0000044319385779090226 ]
{ "id": 3, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tthis.searchWidget.setWidth(this.size.width - 28 /* container margin */);\n", "\n", "\t\tthis.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.size.width >= SearchView.WIDE_VIEW_SIZE) {\n", "\t\t\tthis.getContainer().addClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t} else {\n", "\t\t\tthis.getContainer().removeClass(SearchView.WIDE_CLASS_NAME);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/search/browser/searchView.ts", "type": "add", "edit_start_line_idx": 750 }
/*--------------------------------------------------------------------------------------------- * 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 assert from 'assert'; import 'vs/workbench/browser/parts/editor/editor.contribution'; // make sure to load all contributed editor things into tests import { Promise, TPromise } from 'vs/base/common/winjs.base'; import { Event } from 'vs/base/common/event'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { Registry } from 'vs/platform/registry/common/platform'; import { QuickOpenHandlerDescriptor, IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenAction, QuickOpenHandler } from 'vs/workbench/browser/quickopen'; export class TestQuickOpenService implements IQuickOpenService { public _serviceBrand: any; private callback: (prefix: string) => void; constructor(callback?: (prefix: string) => void) { this.callback = callback; } pick(arg: any, options?: any, token?: any): Promise { return TPromise.as(null); } input(options?: any, token?: any): Promise { return TPromise.as(null); } accept(): void { } focus(): void { } close(): void { } show(prefix?: string, options?: any): Promise { if (this.callback) { this.callback(prefix); } return TPromise.as(true); } get onShow(): Event<void> { return null; } get onHide(): Event<void> { return null; } public dispose() { } public navigate(): void { } } suite('Workbench QuickOpen', () => { class TestHandler extends QuickOpenHandler { } test('QuickOpen Handler and Registry', () => { let registry = (Registry.as<IQuickOpenRegistry>(QuickOpenExtensions.Quickopen)); let handler = new QuickOpenHandlerDescriptor( TestHandler, 'testhandler', ',', 'Handler', null ); registry.registerQuickOpenHandler(handler); assert(registry.getQuickOpenHandler(',') === handler); let handlers = registry.getQuickOpenHandlers(); assert(handlers.some((handler: QuickOpenHandlerDescriptor) => handler.prefix === ',')); }); test('QuickOpen Action', () => { let defaultAction = new QuickOpenAction('id', 'label', void 0, new TestQuickOpenService((prefix: string) => assert(!prefix))); let prefixAction = new QuickOpenAction('id', 'label', ',', new TestQuickOpenService((prefix: string) => assert(!!prefix))); defaultAction.run(); prefixAction.run(); }); });
src/vs/workbench/test/browser/quickopen.test.ts
0
https://github.com/microsoft/vscode/commit/af9dc731ca13b2e65f176a0f56869d95927e6a0d
[ 0.00017595333338249475, 0.00017358973855152726, 0.00016553467139601707, 0.00017423779354430735, 0.000002817279209921253 ]
{ "id": 0, "code_window": [ "import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views';\n", "import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';\n", "import { mark } from 'vs/base/common/performance';\n", "import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';\n", "\n", "export enum Settings {\n", "\tACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible',\n", "\tSTATUSBAR_VISIBLE = 'workbench.statusBar.visible',\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ILogService } from 'vs/platform/log/common/log';\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 49 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.9964776635169983, 0.01688089780509472, 0.00016282750584650785, 0.00017124743317253888, 0.11504093557596207 ]
{ "id": 0, "code_window": [ "import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views';\n", "import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';\n", "import { mark } from 'vs/base/common/performance';\n", "import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';\n", "\n", "export enum Settings {\n", "\tACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible',\n", "\tSTATUSBAR_VISIBLE = 'workbench.statusBar.visible',\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ILogService } from 'vs/platform/log/common/log';\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 49 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M5.56253 2.51577C3.46348 3.4501 2 5.55414 2 7.99999C2 11.3137 4.68629 14 8 14C11.3137 14 14 11.3137 14 7.99999C14 5.32519 12.2497 3.05919 9.83199 2.28482L9.52968 3.23832C11.5429 3.88454 13 5.7721 13 7.99999C13 10.7614 10.7614 13 8 13C5.23858 13 3 10.7614 3 7.99999C3 6.31104 3.83742 4.81767 5.11969 3.91245L5.56253 2.51577Z" fill="#C5C5C5"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M5 3H2V2H5.5L6 2.5V6H5V3Z" fill="#C5C5C5"/> </svg>
extensions/search-result/src/media/refresh-dark.svg
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017188346828334033, 0.00017188346828334033, 0.00017188346828334033, 0.00017188346828334033, 0 ]
{ "id": 0, "code_window": [ "import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views';\n", "import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';\n", "import { mark } from 'vs/base/common/performance';\n", "import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';\n", "\n", "export enum Settings {\n", "\tACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible',\n", "\tSTATUSBAR_VISIBLE = 'workbench.statusBar.visible',\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ILogService } from 'vs/platform/log/common/log';\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 49 }
struct VS_OUTPUT { float4 Position : SV_Position; }; VS_OUTPUT main(in float4 vPosition : POSITION) { VS_OUTPUT Output; Output.Position = vPosition; return Output; }
extensions/hlsl/test/colorize-fixtures/test.hlsl
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017245575145352632, 0.0001680342247709632, 0.00016361268353648484, 0.0001680342247709632, 0.00000442153395852074 ]
{ "id": 0, "code_window": [ "import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views';\n", "import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';\n", "import { mark } from 'vs/base/common/performance';\n", "import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';\n", "\n", "export enum Settings {\n", "\tACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible',\n", "\tSTATUSBAR_VISIBLE = 'workbench.statusBar.visible',\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ILogService } from 'vs/platform/log/common/log';\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 49 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import type * as vscode from 'vscode'; import { ExtHostSearchShape, MainThreadSearchShape, MainContext } from '../common/extHost.protocol'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { FileSearchManager } from 'vs/workbench/services/search/common/fileSearchManager'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService'; import { ILogService } from 'vs/platform/log/common/log'; import { IRawFileQuery, ISearchCompleteStats, IFileQuery, IRawTextQuery, IRawQuery, ITextQuery, IFolderQuery } from 'vs/workbench/services/search/common/search'; import { URI, UriComponents } from 'vs/base/common/uri'; import { TextSearchManager } from 'vs/workbench/services/search/common/textSearchManager'; export interface IExtHostSearch extends ExtHostSearchShape { registerTextSearchProvider(scheme: string, provider: vscode.TextSearchProvider): IDisposable; registerFileSearchProvider(scheme: string, provider: vscode.FileSearchProvider): IDisposable; } export const IExtHostSearch = createDecorator<IExtHostSearch>('IExtHostSearch'); export class ExtHostSearch implements ExtHostSearchShape { protected readonly _proxy: MainThreadSearchShape = this.extHostRpc.getProxy(MainContext.MainThreadSearch); protected _handlePool: number = 0; private readonly _textSearchProvider = new Map<number, vscode.TextSearchProvider>(); private readonly _textSearchUsedSchemes = new Set<string>(); private readonly _fileSearchProvider = new Map<number, vscode.FileSearchProvider>(); private readonly _fileSearchUsedSchemes = new Set<string>(); private readonly _fileSearchManager = new FileSearchManager(); constructor( @IExtHostRpcService private extHostRpc: IExtHostRpcService, @IURITransformerService protected _uriTransformer: IURITransformerService, @ILogService protected _logService: ILogService ) { } protected _transformScheme(scheme: string): string { return this._uriTransformer.transformOutgoingScheme(scheme); } registerTextSearchProvider(scheme: string, provider: vscode.TextSearchProvider): IDisposable { if (this._textSearchUsedSchemes.has(scheme)) { throw new Error(`a text search provider for the scheme '${scheme}' is already registered`); } this._textSearchUsedSchemes.add(scheme); const handle = this._handlePool++; this._textSearchProvider.set(handle, provider); this._proxy.$registerTextSearchProvider(handle, this._transformScheme(scheme)); return toDisposable(() => { this._textSearchUsedSchemes.delete(scheme); this._textSearchProvider.delete(handle); this._proxy.$unregisterProvider(handle); }); } registerFileSearchProvider(scheme: string, provider: vscode.FileSearchProvider): IDisposable { if (this._fileSearchUsedSchemes.has(scheme)) { throw new Error(`a file search provider for the scheme '${scheme}' is already registered`); } this._fileSearchUsedSchemes.add(scheme); const handle = this._handlePool++; this._fileSearchProvider.set(handle, provider); this._proxy.$registerFileSearchProvider(handle, this._transformScheme(scheme)); return toDisposable(() => { this._fileSearchUsedSchemes.delete(scheme); this._fileSearchProvider.delete(handle); this._proxy.$unregisterProvider(handle); }); } $provideFileSearchResults(handle: number, session: number, rawQuery: IRawFileQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> { const query = reviveQuery(rawQuery); const provider = this._fileSearchProvider.get(handle); if (provider) { return this._fileSearchManager.fileSearch(query, provider, batch => { this._proxy.$handleFileMatch(handle, session, batch.map(p => p.resource)); }, token); } else { throw new Error('unknown provider: ' + handle); } } $clearCache(cacheKey: string): Promise<void> { this._fileSearchManager.clearCache(cacheKey); return Promise.resolve(undefined); } $provideTextSearchResults(handle: number, session: number, rawQuery: IRawTextQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> { const provider = this._textSearchProvider.get(handle); if (!provider || !provider.provideTextSearchResults) { throw new Error(`Unknown provider ${handle}`); } const query = reviveQuery(rawQuery); const engine = this.createTextSearchManager(query, provider); return engine.search(progress => this._proxy.$handleTextMatch(handle, session, progress), token); } protected createTextSearchManager(query: ITextQuery, provider: vscode.TextSearchProvider): TextSearchManager { return new TextSearchManager(query, provider, { readdir: resource => Promise.resolve([]), // TODO@rob implement toCanonicalName: encoding => encoding }); } } export function reviveQuery<U extends IRawQuery>(rawQuery: U): U extends IRawTextQuery ? ITextQuery : IFileQuery { return { ...<any>rawQuery, // TODO@rob ??? ...{ folderQueries: rawQuery.folderQueries && rawQuery.folderQueries.map(reviveFolderQuery), extraFileResources: rawQuery.extraFileResources && rawQuery.extraFileResources.map(components => URI.revive(components)) } }; } function reviveFolderQuery(rawFolderQuery: IFolderQuery<UriComponents>): IFolderQuery<URI> { return { ...rawFolderQuery, folder: URI.revive(rawFolderQuery.folder) }; }
src/vs/workbench/api/common/extHostSearch.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00020546226005535573, 0.00017476962239015847, 0.00016715058882255107, 0.00017324193322565407, 0.000008820044058666099 ]
{ "id": 1, "code_window": [ "\tprivate notificationService!: INotificationService;\n", "\tprivate themeService!: IThemeService;\n", "\tprivate activityBarService!: IActivityBarService;\n", "\tprivate statusBarService!: IStatusbarService;\n", "\n", "\tprotected readonly state = {\n", "\t\tfullscreen: false,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tprivate logService!: ILogService;\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 186 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.9983990788459778, 0.06920544058084488, 0.0001625589793547988, 0.00017374711751472205, 0.2418939471244812 ]
{ "id": 1, "code_window": [ "\tprivate notificationService!: INotificationService;\n", "\tprivate themeService!: IThemeService;\n", "\tprivate activityBarService!: IActivityBarService;\n", "\tprivate statusBarService!: IStatusbarService;\n", "\n", "\tprotected readonly state = {\n", "\t\tfullscreen: false,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tprivate logService!: ILogService;\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 186 }
<?xml version='1.0' standalone='no' ?> <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='10px' height='10px'> <style> circle { animation: ball 0.6s linear infinite; } circle:nth-child(2) { animation-delay: 0.075s; } circle:nth-child(3) { animation-delay: 0.15s; } circle:nth-child(4) { animation-delay: 0.225s; } circle:nth-child(5) { animation-delay: 0.3s; } circle:nth-child(6) { animation-delay: 0.375s; } circle:nth-child(7) { animation-delay: 0.45s; } circle:nth-child(8) { animation-delay: 0.525s; } @keyframes ball { from { opacity: 1; } to { opacity: 0.3; } } </style> <g> <circle cx='5' cy='1' r='1' style='opacity:0.3;' /> <circle cx='7.8284' cy='2.1716' r='1' style='opacity:0.3;' /> <circle cx='9' cy='5' r='1' style='opacity:0.3;' /> <circle cx='7.8284' cy='7.8284' r='1' style='opacity:0.3;' /> <circle cx='5' cy='9' r='1' style='opacity:0.3;' /> <circle cx='2.1716' cy='7.8284' r='1' style='opacity:0.3;' /> <circle cx='1' cy='5' r='1' style='opacity:0.3;' /> <circle cx='2.1716' cy='2.1716' r='1' style='opacity:0.3;' /> </g> </svg>
extensions/image-preview/media/loading.svg
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017905441927723587, 0.00017602546722628176, 0.00017046317225322127, 0.00017729215323925018, 0.0000032993850709317485 ]
{ "id": 1, "code_window": [ "\tprivate notificationService!: INotificationService;\n", "\tprivate themeService!: IThemeService;\n", "\tprivate activityBarService!: IActivityBarService;\n", "\tprivate statusBarService!: IStatusbarService;\n", "\n", "\tprotected readonly state = {\n", "\t\tfullscreen: false,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tprivate logService!: ILogService;\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 186 }
/*--------------------------------------------------------------------------------------------- * 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 interface Command { readonly id: string | string[]; execute(...args: any[]): void; } export class CommandManager { private readonly commands = new Map<string, vscode.Disposable>(); public dispose() { for (const registration of this.commands.values()) { registration.dispose(); } this.commands.clear(); } public register<T extends Command>(command: T): T { for (const id of Array.isArray(command.id) ? command.id : [command.id]) { this.registerCommand(id, command.execute, command); } return command; } private registerCommand(id: string, impl: (...args: any[]) => void, thisArg?: any) { if (this.commands.has(id)) { return; } this.commands.set(id, vscode.commands.registerCommand(id, impl, thisArg)); } }
extensions/typescript-language-features/src/commands/commandManager.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017674884293228388, 0.00017437317001167685, 0.00017317468882538378, 0.00017378455959260464, 0.0000013941134966444224 ]
{ "id": 1, "code_window": [ "\tprivate notificationService!: INotificationService;\n", "\tprivate themeService!: IThemeService;\n", "\tprivate activityBarService!: IActivityBarService;\n", "\tprivate statusBarService!: IStatusbarService;\n", "\n", "\tprotected readonly state = {\n", "\t\tfullscreen: false,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tprivate logService!: ILogService;\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 186 }
{ "name": "github-authentication", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "version": "0.0.1", "engines": { "vscode": "^1.41.0" }, "enableProposedApi": true, "categories": [ "Other" ], "extensionKind": [ "ui", "workspace", "web" ], "activationEvents": [ "onAuthenticationRequest:github" ], "contributes": { "commands": [ { "command": "github.provide-token", "title": "Manually Provide Token" } ], "menus": { "commandPalette": [ { "command": "github.provide-token", "when": "false" } ] }, "authentication": [ { "label": "GitHub", "id": "github" } ] }, "aiKey": "AIF-d9b70cd4-b9f9-4d70-929b-a071c400b217", "main": "./out/extension.js", "browser": "./dist/browser/extension.js", "scripts": { "compile": "gulp compile-extension:github-authentication", "compile-web": "npx webpack-cli --config extension-browser.webpack.config --mode none", "watch": "gulp watch-extension:github-authentication", "watch-web": "npx webpack-cli --config extension-browser.webpack.config --mode none --watch --info-verbosity verbose", "vscode:prepublish": "npm run compile" }, "dependencies": { "node-fetch": "2.6.0", "uuid": "8.1.0", "vscode-extension-telemetry": "0.1.1", "vscode-nls": "^4.1.2" }, "devDependencies": { "@types/keytar": "^4.4.2", "@types/node": "^10.12.21", "@types/node-fetch": "2.5.7", "@types/uuid": "8.0.0", "typescript": "^3.7.5" } }
extensions/github-authentication/package.json
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0001756114070303738, 0.00017273931007366627, 0.00016901835624594241, 0.0001724108587950468, 0.000002096670641549281 ]
{ "id": 2, "code_window": [ "\t\tthis.contextService = accessor.get(IWorkspaceContextService);\n", "\t\tthis.storageService = accessor.get(IStorageService);\n", "\t\tthis.backupFileService = accessor.get(IBackupFileService);\n", "\t\tthis.themeService = accessor.get(IThemeService);\n", "\t\tthis.extensionService = accessor.get(IExtensionService);\n", "\n", "\t\t// Parts\n", "\t\tthis.editorService = accessor.get(IEditorService);\n", "\t\tthis.editorGroupService = accessor.get(IEditorGroupsService);\n", "\t\tthis.panelService = accessor.get(IPanelService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.logService = accessor.get(ILogService);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 265 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.9984460473060608, 0.0059509300626814365, 0.00016165240958798677, 0.000173779611941427, 0.07241541892290115 ]
{ "id": 2, "code_window": [ "\t\tthis.contextService = accessor.get(IWorkspaceContextService);\n", "\t\tthis.storageService = accessor.get(IStorageService);\n", "\t\tthis.backupFileService = accessor.get(IBackupFileService);\n", "\t\tthis.themeService = accessor.get(IThemeService);\n", "\t\tthis.extensionService = accessor.get(IExtensionService);\n", "\n", "\t\t// Parts\n", "\t\tthis.editorService = accessor.get(IEditorService);\n", "\t\tthis.editorGroupService = accessor.get(IEditorGroupsService);\n", "\t\tthis.panelService = accessor.get(IPanelService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.logService = accessor.get(ILogService);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 265 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export function toBase64UrlEncoding(base64string: string) { return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); // Need to use base64url encoding }
extensions/microsoft-authentication/src/utils.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017269517411477864, 0.00017269517411477864, 0.00017269517411477864, 0.00017269517411477864, 0 ]
{ "id": 2, "code_window": [ "\t\tthis.contextService = accessor.get(IWorkspaceContextService);\n", "\t\tthis.storageService = accessor.get(IStorageService);\n", "\t\tthis.backupFileService = accessor.get(IBackupFileService);\n", "\t\tthis.themeService = accessor.get(IThemeService);\n", "\t\tthis.extensionService = accessor.get(IExtensionService);\n", "\n", "\t\t// Parts\n", "\t\tthis.editorService = accessor.get(IEditorService);\n", "\t\tthis.editorGroupService = accessor.get(IEditorGroupsService);\n", "\t\tthis.panelService = accessor.get(IPanelService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.logService = accessor.get(ILogService);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 265 }
/*--------------------------------------------------------------------------------------------- * 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 platform from 'vs/base/common/platform'; import { fixDriveC, getAbsoluteGlob } from 'vs/workbench/services/search/node/ripgrepFileSearch'; suite('RipgrepFileSearch - etc', () => { function testGetAbsGlob(params: string[]): void { const [folder, glob, expectedResult] = params; assert.equal(fixDriveC(getAbsoluteGlob(folder, glob)), expectedResult, JSON.stringify(params)); } test('getAbsoluteGlob_win', () => { if (!platform.isWindows) { return; } [ ['C:/foo/bar', 'glob/**', '/foo\\bar\\glob\\**'], ['c:/', 'glob/**', '/glob\\**'], ['C:\\foo\\bar', 'glob\\**', '/foo\\bar\\glob\\**'], ['c:\\foo\\bar', 'glob\\**', '/foo\\bar\\glob\\**'], ['c:\\', 'glob\\**', '/glob\\**'], ['\\\\localhost\\c$\\foo\\bar', 'glob/**', '\\\\localhost\\c$\\foo\\bar\\glob\\**'], // absolute paths are not resolved further ['c:/foo/bar', '/path/something', '/path/something'], ['c:/foo/bar', 'c:\\project\\folder', '/project\\folder'] ].forEach(testGetAbsGlob); }); test('getAbsoluteGlob_posix', () => { if (platform.isWindows) { return; } [ ['/foo/bar', 'glob/**', '/foo/bar/glob/**'], ['/', 'glob/**', '/glob/**'], // absolute paths are not resolved further ['/', '/project/folder', '/project/folder'], ].forEach(testGetAbsGlob); }); });
src/vs/workbench/services/search/test/node/ripgrepFileSearch.test.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017363698862027377, 0.0001724444009596482, 0.00016993380268104374, 0.00017270045646000654, 0.0000013057613159617176 ]
{ "id": 2, "code_window": [ "\t\tthis.contextService = accessor.get(IWorkspaceContextService);\n", "\t\tthis.storageService = accessor.get(IStorageService);\n", "\t\tthis.backupFileService = accessor.get(IBackupFileService);\n", "\t\tthis.themeService = accessor.get(IThemeService);\n", "\t\tthis.extensionService = accessor.get(IExtensionService);\n", "\n", "\t\t// Parts\n", "\t\tthis.editorService = accessor.get(IEditorService);\n", "\t\tthis.editorGroupService = accessor.get(IEditorGroupsService);\n", "\t\tthis.panelService = accessor.get(IPanelService);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.logService = accessor.get(ILogService);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 265 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import * as paths from 'vs/base/common/path'; import { Emitter } from 'vs/base/common/event'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { Registry } from 'vs/platform/registry/common/platform'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IWorkspaceContextService, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { basenameOrAuthority, basename, joinPath, dirname } from 'vs/base/common/resources'; import { tildify, getPathLabel } from 'vs/base/common/labels'; import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, WORKSPACE_EXTENSION, toWorkspaceIdentifier, isWorkspaceIdentifier, isUntitledWorkspace } from 'vs/platform/workspaces/common/workspaces'; import { ILabelService, ResourceLabelFormatter, ResourceLabelFormatting, IFormatterChangeEvent } from 'vs/platform/label/common/label'; import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry'; import { match } from 'vs/base/common/glob'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; const resourceLabelFormattersExtPoint = ExtensionsRegistry.registerExtensionPoint<ResourceLabelFormatter[]>({ extensionPoint: 'resourceLabelFormatters', jsonSchema: { description: localize('vscode.extension.contributes.resourceLabelFormatters', 'Contributes resource label formatting rules.'), type: 'array', items: { type: 'object', required: ['scheme', 'formatting'], properties: { scheme: { type: 'string', description: localize('vscode.extension.contributes.resourceLabelFormatters.scheme', 'URI scheme on which to match the formatter on. For example "file". Simple glob patterns are supported.'), }, authority: { type: 'string', description: localize('vscode.extension.contributes.resourceLabelFormatters.authority', 'URI authority on which to match the formatter on. Simple glob patterns are supported.'), }, formatting: { description: localize('vscode.extension.contributes.resourceLabelFormatters.formatting', "Rules for formatting uri resource labels."), type: 'object', properties: { label: { type: 'string', description: localize('vscode.extension.contributes.resourceLabelFormatters.label', "Label rules to display. For example: myLabel:/${path}. ${path}, ${scheme} and ${authority} are supported as variables.") }, separator: { type: 'string', description: localize('vscode.extension.contributes.resourceLabelFormatters.separator', "Separator to be used in the uri label display. '/' or '\' as an example.") }, stripPathStartingSeparator: { type: 'boolean', description: localize('vscode.extension.contributes.resourceLabelFormatters.stripPathStartingSeparator', "Controls whether `${path}` substitutions should have starting separator characters stripped.") }, tildify: { type: 'boolean', description: localize('vscode.extension.contributes.resourceLabelFormatters.tildify', "Controls if the start of the uri label should be tildified when possible.") }, workspaceSuffix: { type: 'string', description: localize('vscode.extension.contributes.resourceLabelFormatters.formatting.workspaceSuffix', "Suffix appended to the workspace label.") } } } } } } }); const sepRegexp = /\//g; const labelMatchingRegexp = /\$\{(scheme|authority|path|(query)\.(.+?))\}/g; function hasDriveLetter(path: string): boolean { return !!(path && path[2] === ':'); } class ResourceLabelFormattersHandler implements IWorkbenchContribution { private formattersDisposables = new Map<ResourceLabelFormatter, IDisposable>(); constructor(@ILabelService labelService: ILabelService) { resourceLabelFormattersExtPoint.setHandler((extensions, delta) => { delta.added.forEach(added => added.value.forEach(formatter => { this.formattersDisposables.set(formatter, labelService.registerFormatter(formatter)); })); delta.removed.forEach(removed => removed.value.forEach(formatter => { this.formattersDisposables.get(formatter)!.dispose(); })); }); } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(ResourceLabelFormattersHandler, LifecyclePhase.Restored); export class LabelService extends Disposable implements ILabelService { declare readonly _serviceBrand: undefined; private formatters: ResourceLabelFormatter[] = []; private readonly _onDidChangeFormatters = this._register(new Emitter<IFormatterChangeEvent>()); readonly onDidChangeFormatters = this._onDidChangeFormatters.event; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IPathService private readonly pathService: IPathService ) { super(); } findFormatting(resource: URI): ResourceLabelFormatting | undefined { let bestResult: ResourceLabelFormatter | undefined; this.formatters.forEach(formatter => { if (formatter.scheme === resource.scheme) { if (!bestResult && !formatter.authority) { bestResult = formatter; return; } if (!formatter.authority) { return; } if (match(formatter.authority.toLowerCase(), resource.authority.toLowerCase()) && (!bestResult || !bestResult.authority || formatter.authority.length > bestResult.authority.length || ((formatter.authority.length === bestResult.authority.length) && formatter.priority))) { bestResult = formatter; } } }); return bestResult ? bestResult.formatting : undefined; } getUriLabel(resource: URI, options: { relative?: boolean, noPrefix?: boolean, endWithSeparator?: boolean } = {}): string { return this.doGetUriLabel(resource, this.findFormatting(resource), options); } private doGetUriLabel(resource: URI, formatting?: ResourceLabelFormatting, options: { relative?: boolean, noPrefix?: boolean, endWithSeparator?: boolean } = {}): string { if (!formatting) { return getPathLabel(resource.path, { userHome: this.pathService.resolvedUserHome }, options.relative ? this.contextService : undefined); } let label: string | undefined; const baseResource = this.contextService?.getWorkspaceFolder(resource); if (options.relative && baseResource) { const baseResourceLabel = this.formatUri(baseResource.uri, formatting, options.noPrefix); let relativeLabel = this.formatUri(resource, formatting, options.noPrefix); let overlap = 0; while (relativeLabel[overlap] && relativeLabel[overlap] === baseResourceLabel[overlap]) { overlap++; } if (!relativeLabel[overlap] || relativeLabel[overlap] === formatting.separator) { relativeLabel = relativeLabel.substring(1 + overlap); } const hasMultipleRoots = this.contextService.getWorkspace().folders.length > 1; if (hasMultipleRoots && !options.noPrefix) { const rootName = baseResource?.name ?? basenameOrAuthority(baseResource.uri); relativeLabel = relativeLabel ? (rootName + ' • ' + relativeLabel) : rootName; // always show root basename if there are multiple } label = relativeLabel; } else { label = this.formatUri(resource, formatting, options.noPrefix); } return options.endWithSeparator ? this.appendSeparatorIfMissing(label, formatting) : label; } getUriBasenameLabel(resource: URI): string { const formatting = this.findFormatting(resource); const label = this.doGetUriLabel(resource, formatting); if (formatting) { switch (formatting.separator) { case paths.win32.sep: return paths.win32.basename(label); case paths.posix.sep: return paths.posix.basename(label); } } return paths.basename(label); } getWorkspaceLabel(workspace: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IWorkspace), options?: { verbose: boolean }): string { if (IWorkspace.isIWorkspace(workspace)) { const identifier = toWorkspaceIdentifier(workspace); if (!identifier) { return ''; } workspace = identifier; } // Workspace: Single Folder if (isSingleFolderWorkspaceIdentifier(workspace)) { // Folder on disk const label = options && options.verbose ? this.getUriLabel(workspace) : basename(workspace) || '/'; return this.appendWorkspaceSuffix(label, workspace); } if (isWorkspaceIdentifier(workspace)) { // Workspace: Untitled if (isUntitledWorkspace(workspace.configPath, this.environmentService)) { return localize('untitledWorkspace', "Untitled (Workspace)"); } // Workspace: Saved let filename = basename(workspace.configPath); if (filename.endsWith(WORKSPACE_EXTENSION)) { filename = filename.substr(0, filename.length - WORKSPACE_EXTENSION.length - 1); } let label; if (options && options.verbose) { label = localize('workspaceNameVerbose', "{0} (Workspace)", this.getUriLabel(joinPath(dirname(workspace.configPath), filename))); } else { label = localize('workspaceName', "{0} (Workspace)", filename); } return this.appendWorkspaceSuffix(label, workspace.configPath); } return ''; } getSeparator(scheme: string, authority?: string): '/' | '\\' { const formatter = this.findFormatting(URI.from({ scheme, authority })); return formatter && formatter.separator || '/'; } getHostLabel(scheme: string, authority?: string): string { const formatter = this.findFormatting(URI.from({ scheme, authority })); return formatter && formatter.workspaceSuffix || ''; } registerFormatter(formatter: ResourceLabelFormatter): IDisposable { this.formatters.push(formatter); this._onDidChangeFormatters.fire({ scheme: formatter.scheme }); return { dispose: () => { this.formatters = this.formatters.filter(f => f !== formatter); this._onDidChangeFormatters.fire({ scheme: formatter.scheme }); } }; } private formatUri(resource: URI, formatting: ResourceLabelFormatting, forceNoTildify?: boolean): string { let label = formatting.label.replace(labelMatchingRegexp, (match, token, qsToken, qsValue) => { switch (token) { case 'scheme': return resource.scheme; case 'authority': return resource.authority; case 'path': return formatting.stripPathStartingSeparator ? resource.path.slice(resource.path[0] === formatting.separator ? 1 : 0) : resource.path; default: { if (qsToken === 'query') { const { query } = resource; if (query && query[0] === '{' && query[query.length - 1] === '}') { try { return JSON.parse(query)[qsValue] || ''; } catch { } } } return ''; } } }); // convert \c:\something => C:\something if (formatting.normalizeDriveLetter && hasDriveLetter(label)) { label = label.charAt(1).toUpperCase() + label.substr(2); } if (formatting.tildify && !forceNoTildify) { const userHome = this.pathService.resolvedUserHome; if (userHome) { label = tildify(label, userHome.fsPath); } } if (formatting.authorityPrefix && resource.authority) { label = formatting.authorityPrefix + label; } return label.replace(sepRegexp, formatting.separator); } private appendSeparatorIfMissing(label: string, formatting: ResourceLabelFormatting): string { let appendedLabel = label; if (!label.endsWith(formatting.separator)) { appendedLabel += formatting.separator; } return appendedLabel; } private appendWorkspaceSuffix(label: string, uri: URI): string { const formatting = this.findFormatting(uri); const suffix = formatting && (typeof formatting.workspaceSuffix === 'string') ? formatting.workspaceSuffix : undefined; return suffix ? `${label} [${suffix}]` : label; } } registerSingleton(ILabelService, LabelService, true);
src/vs/workbench/services/label/common/labelService.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0012132128467783332, 0.000211654813028872, 0.00016283434524666518, 0.0001731316006043926, 0.00018404419824946672 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tlayout(): void {\n", "\t\tif (!this.disposed) {\n", "\t\t\tthis._dimension = this.getClientArea();\n", "\n", "\t\t\tposition(this.container, 0, 0, 0, 0, 'relative');\n", "\t\t\tsize(this.container, this._dimension.width, this._dimension.height);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.logService.trace(`Layout#layout, height: ${this._dimension.height}, width: ${this._dimension.width}`);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 1346 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.997916042804718, 0.04262852668762207, 0.00016242526180576533, 0.000172181855305098, 0.19906602799892426 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tlayout(): void {\n", "\t\tif (!this.disposed) {\n", "\t\t\tthis._dimension = this.getClientArea();\n", "\n", "\t\t\tposition(this.container, 0, 0, 0, 0, 'relative');\n", "\t\t\tsize(this.container, this._dimension.width, this._dimension.height);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.logService.trace(`Layout#layout, height: ${this._dimension.height}, width: ${this._dimension.width}`);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 1346 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MainContext, MainThreadLanguagesShape, IMainContext } from './extHost.protocol'; import type * as vscode from 'vscode'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters'; import { StandardTokenType, Range, Position } from 'vs/workbench/api/common/extHostTypes'; export class ExtHostLanguages { private readonly _proxy: MainThreadLanguagesShape; private readonly _documents: ExtHostDocuments; constructor( mainContext: IMainContext, documents: ExtHostDocuments ) { this._proxy = mainContext.getProxy(MainContext.MainThreadLanguages); this._documents = documents; } getLanguages(): Promise<string[]> { return this._proxy.$getLanguages(); } async changeLanguage(uri: vscode.Uri, languageId: string): Promise<vscode.TextDocument> { await this._proxy.$changeLanguage(uri, languageId); const data = this._documents.getDocumentData(uri); if (!data) { throw new Error(`document '${uri.toString}' NOT found`); } return data.document; } async tokenAtPosition(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.TokenInformation> { const versionNow = document.version; const pos = typeConvert.Position.from(position); const info = await this._proxy.$tokensAtPosition(document.uri, pos); const defaultRange = { type: StandardTokenType.Other, range: document.getWordRangeAtPosition(position) ?? new Range(position.line, position.character, position.line, position.character) }; if (!info) { // no result return defaultRange; } const result = { range: typeConvert.Range.to(info.range), type: typeConvert.TokenType.to(info.type) }; if (!result.range.contains(<Position>position)) { // bogous result return defaultRange; } if (versionNow !== document.version) { // concurrent change return defaultRange; } return result; } }
src/vs/workbench/api/common/extHostLanguages.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017771037528291345, 0.0001696690742392093, 0.00016375456470996141, 0.0001683036534814164, 0.000004676835487771314 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tlayout(): void {\n", "\t\tif (!this.disposed) {\n", "\t\t\tthis._dimension = this.getClientArea();\n", "\n", "\t\t\tposition(this.container, 0, 0, 0, 0, 'relative');\n", "\t\t\tsize(this.container, this._dimension.width, this._dimension.height);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.logService.trace(`Layout#layout, height: ${this._dimension.height}, width: ${this._dimension.width}`);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 1346 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench .terminal-widget-container { position: absolute; left: 0; bottom: 0; right: 0; top: 0; overflow: visible; } .monaco-workbench .terminal-overlay-widget { position: absolute; left: 0; bottom: 0; color: #3794ff; } .monaco-workbench .terminal-hover-target { position: absolute; z-index: 30; } .monaco-workbench .terminal-env-var-info { position: absolute; right: 2px; top: 0; width: 28px; height: 28px; text-align: center; z-index: 10; opacity: 0.5; } .monaco-workbench .terminal-env-var-info:hover, .monaco-workbench .terminal-env-var-info.requires-action { opacity: 1; } .monaco-workbench .pane-body.integrated-terminal .monaco-split-view2.horizontal .split-view-view:last-child .terminal-env-var-info { /* Adjust for reduced margin in splits */ right: -8px; } .monaco-workbench .terminal-env-var-info.codicon { line-height: 28px; }
src/vs/workbench/contrib/terminal/browser/media/widgets.css
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.000172852334799245, 0.0001689190394245088, 0.00016549156862311065, 0.0001690678473096341, 0.0000028609811124624684 ]
{ "id": 3, "code_window": [ "\t}\n", "\n", "\tlayout(): void {\n", "\t\tif (!this.disposed) {\n", "\t\t\tthis._dimension = this.getClientArea();\n", "\n", "\t\t\tposition(this.container, 0, 0, 0, 0, 'relative');\n", "\t\t\tsize(this.container, this._dimension.width, this._dimension.height);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.logService.trace(`Layout#layout, height: ${this._dimension.height}, width: ${this._dimension.width}`);\n" ], "file_path": "src/vs/workbench/browser/layout.ts", "type": "add", "edit_start_line_idx": 1346 }
{ "version": "0.1.0", "configurations": [ { "type": "node", "request": "launch", "name": "Gulp Build", "program": "${workspaceFolder}/node_modules/gulp/bin/gulp.js", "stopOnEntry": true, "args": [ "hygiene" ] }, { "type": "node", "request": "attach", "restart": true, "name": "Attach to Extension Host", "timeout": 30000, "port": 5870, "outFiles": [ "${workspaceFolder}/out/**/*.js", "${workspaceFolder}/extensions/*/out/**/*.js" ] }, { "type": "pwa-chrome", "request": "attach", "name": "Attach to Shared Process", "timeout": 30000, "port": 9222, "urlFilter": "*sharedProcess.html*", "presentation": { "hidden": true } }, { "type": "node", "request": "attach", "name": "Attach to Search Process", "port": 5876, "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "hidden": true, } }, { "type": "node", "request": "attach", "name": "Attach to CLI Process", "port": 5874, "outFiles": [ "${workspaceFolder}/out/**/*.js" ] }, { "type": "node", "request": "attach", "name": "Attach to Main Process", "timeout": 30000, "port": 5875, "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "hidden": true, } }, { "type": "extensionHost", "request": "launch", "name": "VS Code Emmet Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/emmet/test-fixtures", "--extensionDevelopmentPath=${workspaceFolder}/extensions/emmet", "--extensionTestsPath=${workspaceFolder}/extensions/emmet/out/test" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 6 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code Git Tests", "runtimeExecutable": "${execPath}", "args": [ "/tmp/my4g9l", "--extensionDevelopmentPath=${workspaceFolder}/extensions/git", "--extensionTestsPath=${workspaceFolder}/extensions/git/out/test" ], "outFiles": [ "${workspaceFolder}/extensions/git/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 6 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code API Tests (single folder)", "runtimeExecutable": "${execPath}", "args": [ // "${workspaceFolder}", // Uncomment for running out of sources. "${workspaceFolder}/extensions/vscode-api-tests/testWorkspace", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode-api-tests", "--extensionTestsPath=${workspaceFolder}/extensions/vscode-api-tests/out/singlefolder-tests" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 3 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code API Tests (workspace)", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/vscode-api-tests/testworkspace.code-workspace", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode-api-tests", "--extensionTestsPath=${workspaceFolder}/extensions/vscode-api-tests/out/workspace-tests" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 4 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code Tokenizer Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/vscode-colorize-tests/test", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode-colorize-tests", "--extensionTestsPath=${workspaceFolder}/extensions/vscode-colorize-tests/out" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 5 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code Notebook Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/vscode-notebook-tests/test", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode-notebook-tests", "--extensionTestsPath=${workspaceFolder}/extensions/vscode-notebook-tests/out" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 6 } }, { "type": "extensionHost", "request": "launch", "name": "VS Code Custom Editor Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/vscode-custom-editor-tests/test-workspace", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode-custom-editor-tests", "--extensionTestsPath=${workspaceFolder}/extensions/vscode-custom-editor-tests/out/test" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 6 } }, { "type": "pwa-chrome", "request": "attach", "name": "Attach to VS Code", "browserAttachLocation": "workspace", "port": 9222 }, { "type": "pwa-chrome", "request": "launch", "name": "Launch VS Code", "windows": { "runtimeExecutable": "${workspaceFolder}/scripts/code.bat" }, "osx": { "runtimeExecutable": "${workspaceFolder}/scripts/code.sh" }, "linux": { "runtimeExecutable": "${workspaceFolder}/scripts/code.sh" }, "port": 9222, "timeout": 20000, "env": { "VSCODE_EXTHOST_WILL_SEND_SOCKET": null, "VSCODE_SKIP_PRELAUNCH": "1" }, "cleanUp": "wholeBrowser", "urlFilter": "*workbench.html*", "runtimeArgs": [ "--inspect=5875", "--no-cached-data", ], "webRoot": "${workspaceFolder}", "cascadeTerminateToConfigurations": [ "Attach to Extension Host" ], "userDataDir": false, "pauseForSourceMap": false, "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "browserLaunchLocation": "workspace", "preLaunchTask": "Ensure Prelaunch Dependencies", }, { "type": "node", "request": "launch", "name": "VS Code (Web)", "program": "${workspaceFolder}/resources/web/code-web.js", "presentation": { "group": "0_vscode", "order": 2 } }, { "type": "node", "request": "launch", "name": "Main Process", "runtimeExecutable": "${workspaceFolder}/scripts/code.sh", "windows": { "runtimeExecutable": "${workspaceFolder}/scripts/code.bat", }, "runtimeArgs": [ "--no-cached-data" ], "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "presentation": { "group": "1_vscode", "order": 1 } }, { "type": "chrome", "request": "launch", "name": "VS Code (Web, Chrome)", "url": "http://localhost:8080", "preLaunchTask": "Run web", "presentation": { "group": "0_vscode", "order": 3 } }, { "type": "pwa-msedge", "request": "launch", "name": "VS Code (Web, Edge)", "url": "http://localhost:8080", "pauseForSourceMap": false, "preLaunchTask": "Run web", "presentation": { "group": "0_vscode", "order": 3 } }, { "type": "node", "request": "launch", "name": "Git Unit Tests", "program": "${workspaceFolder}/extensions/git/node_modules/mocha/bin/_mocha", "stopOnEntry": false, "cwd": "${workspaceFolder}/extensions/git", "outFiles": [ "${workspaceFolder}/extensions/git/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 10 } }, { "type": "node", "request": "launch", "name": "HTML Server Unit Tests", "program": "${workspaceFolder}/extensions/html-language-features/server/test/index.js", "stopOnEntry": false, "cwd": "${workspaceFolder}/extensions/html-language-features/server", "outFiles": [ "${workspaceFolder}/extensions/html-language-features/server/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 10 } }, { "type": "node", "request": "launch", "name": "CSS Server Unit Tests", "program": "${workspaceFolder}/extensions/css-language-features/server/test/index.js", "stopOnEntry": false, "cwd": "${workspaceFolder}/extensions/css-language-features/server", "outFiles": [ "${workspaceFolder}/extensions/css-language-features/server/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 10 } }, { "type": "extensionHost", "request": "launch", "name": "Markdown Extension Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/markdown-language-features/test-workspace", "--extensionDevelopmentPath=${workspaceFolder}/extensions/markdown-language-features", "--extensionTestsPath=${workspaceFolder}/extensions/markdown-language-features/out/test" ], "outFiles": [ "${workspaceFolder}/extensions/markdown-language-features/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 7 } }, { "type": "extensionHost", "request": "launch", "name": "TypeScript Extension Tests", "runtimeExecutable": "${execPath}", "args": [ "${workspaceFolder}/extensions/typescript-language-features/test-workspace", "--extensionDevelopmentPath=${workspaceFolder}/extensions/typescript-language-features", "--extensionTestsPath=${workspaceFolder}/extensions/typescript-language-features/out/test" ], "outFiles": [ "${workspaceFolder}/extensions/typescript-language-features/out/**/*.js" ], "presentation": { "group": "5_tests", "order": 8 } }, { "type": "node", "request": "launch", "name": "Run Unit Tests", "program": "${workspaceFolder}/test/unit/electron/index.js", "runtimeExecutable": "${workspaceFolder}/.build/electron/Code - OSS.app/Contents/MacOS/Electron", "windows": { "runtimeExecutable": "${workspaceFolder}/.build/electron/Code - OSS.exe" }, "linux": { "runtimeExecutable": "${workspaceFolder}/.build/electron/code-oss" }, "outputCapture": "std", "args": [ "--remote-debugging-port=9222" ], "cwd": "${workspaceFolder}", "outFiles": [ "${workspaceFolder}/out/**/*.js" ], "env": { "MOCHA_COLORS": "true" }, "presentation": { "hidden": true } }, { "type": "node", "request": "launch", "name": "Launch Smoke Test", "program": "${workspaceFolder}/test/smoke/out/main.js", "cwd": "${workspaceFolder}/test/smoke", "timeout": 240000, "port": 9999, "args": [ "-l", "${workspaceFolder}/.build/electron/Code - OSS.app/Contents/MacOS/Electron" ], "outFiles": [ "${cwd}/out/**/*.js" ], "env": { "NODE_ENV": "development", "VSCODE_DEV": "1", "VSCODE_CLI": "1" } }, { "name": "Launch Built-in Extension", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceRoot}/extensions/debug-auto-launch" ] } ], "compounds": [ { "name": "VS Code", "stopAll": true, "configurations": [ "Launch VS Code", "Attach to Main Process", "Attach to Extension Host", "Attach to Shared Process", ], "preLaunchTask": "Ensure Prelaunch Dependencies", "presentation": { "group": "0_vscode", "order": 1 } }, { "name": "Search and Renderer processes", "configurations": [ "Launch VS Code", "Attach to Search Process" ], "presentation": { "group": "1_vscode", "order": 4 } }, { "name": "Renderer and Extension Host processes", "configurations": [ "Launch VS Code", "Attach to Extension Host" ], "presentation": { "group": "1_vscode", "order": 3 } }, { "name": "Debug Unit Tests", "configurations": [ "Attach to VS Code", "Run Unit Tests" ], "presentation": { "group": "1_vscode", "order": 2 } } ] }
.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0001769316295394674, 0.00017230001685675234, 0.0001683567970758304, 0.00017233377730008215, 0.0000016271782214971608 ]
{ "id": 4, "code_window": [ "\t\t);\n", "\n", "\t\t// Listeners\n", "\t\tthis.registerListeners(workbench, services.storageService);\n", "\n", "\t\t// Driver\n", "\t\tif (this.configuration.driver) {\n", "\t\t\t(async () => this._register(await registerWindowDriver()))();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.registerListeners(workbench, services.storageService, services.logService);\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0013697427930310369, 0.00019662700651679188, 0.00016222853446379304, 0.0001726736081764102, 0.00012103213521186262 ]
{ "id": 4, "code_window": [ "\t\t);\n", "\n", "\t\t// Listeners\n", "\t\tthis.registerListeners(workbench, services.storageService);\n", "\n", "\t\t// Driver\n", "\t\tif (this.configuration.driver) {\n", "\t\t\t(async () => this._register(await registerWindowDriver()))();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.registerListeners(workbench, services.storageService, services.logService);\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 86 }
{ "version": "0.2.0", "compounds": [ { "name": "Debug Extension and Language Server", "configurations": [ "Launch Extension", "Attach Language Server" ] } ], "configurations": [ { "name": "Launch Extension", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}" ], "stopOnEntry": false, "sourceMaps": true, "outFiles": [ "${workspaceFolder}/client/out/**/*.js" ], "smartStep": true }, { "name": "Launch Tests", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/client/out/test" ], "stopOnEntry": false, "sourceMaps": true, "outFiles": [ "${workspaceFolder}/client/out/test/**/*.js" ] }, { "name": "Attach Language Server", "type": "node", "request": "attach", "protocol": "inspector", "port": 6044, "sourceMaps": true, "outFiles": [ "${workspaceFolder}/server/out/**/*.js" ], "smartStep": true, "restart": true }, { "name": "Server Unit Tests", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", "stopOnEntry": false, "args": [ "--timeout", "999999", "--colors" ], "cwd": "${workspaceRoot}", "runtimeExecutable": null, "runtimeArgs": [], "env": {}, "sourceMaps": true, "outFiles": [ "${workspaceRoot}/server/out/**" ] } ] }
extensions/css-language-features/.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017734154243953526, 0.00017436410416848958, 0.00017296131409239024, 0.00017419265350326896, 0.0000012951487633472425 ]
{ "id": 4, "code_window": [ "\t\t);\n", "\n", "\t\t// Listeners\n", "\t\tthis.registerListeners(workbench, services.storageService);\n", "\n", "\t\t// Driver\n", "\t\tif (this.configuration.driver) {\n", "\t\t\t(async () => this._register(await registerWindowDriver()))();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.registerListeners(workbench, services.storageService, services.logService);\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { WorkbenchState, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { URI } from 'vs/base/common/uri'; export type Tags = { [index: string]: boolean | number | string | undefined }; export const IWorkspaceTagsService = createDecorator<IWorkspaceTagsService>('workspaceTagsService'); export interface IWorkspaceTagsService { readonly _serviceBrand: undefined; getTags(): Promise<Tags>; /** * Returns an id for the workspace, different from the id returned by the context service. A hash based * on the folder uri or workspace configuration, not time-based, and undefined for empty workspaces. */ getTelemetryWorkspaceId(workspace: IWorkspace, state: WorkbenchState): string | undefined; getHashedRemotesFromUri(workspaceUri: URI, stripEndingDotGit?: boolean): Promise<string[]>; }
src/vs/workbench/contrib/tags/common/workspaceTags.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017384755483362824, 0.000171632447745651, 0.00016946712275967002, 0.00017158266564365476, 0.0000017886503655972774 ]
{ "id": 4, "code_window": [ "\t\t);\n", "\n", "\t\t// Listeners\n", "\t\tthis.registerListeners(workbench, services.storageService);\n", "\n", "\t\t// Driver\n", "\t\tif (this.configuration.driver) {\n", "\t\t\t(async () => this._register(await registerWindowDriver()))();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.registerListeners(workbench, services.storageService, services.logService);\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import type * as Proto from '../protocol'; import { ClientCapability, ITypeScriptServiceClient } from '../typescriptService'; import API from '../utils/api'; import { Delayer } from '../utils/async'; import { nulToken } from '../utils/cancellation'; import { conditionalRegistration, requireSomeCapability, requireMinVersion } from '../utils/dependentRegistration'; import { Disposable } from '../utils/dispose'; import * as fileSchemes from '../utils/fileSchemes'; import { doesResourceLookLikeATypeScriptFile } from '../utils/languageDescription'; import * as typeConverters from '../utils/typeConverters'; import FileConfigurationManager from './fileConfigurationManager'; const localize = nls.loadMessageBundle(); const updateImportsOnFileMoveName = 'updateImportsOnFileMove.enabled'; async function isDirectory(resource: vscode.Uri): Promise<boolean> { try { return (await vscode.workspace.fs.stat(resource)).type === vscode.FileType.Directory; } catch { return false; } } const enum UpdateImportsOnFileMoveSetting { Prompt = 'prompt', Always = 'always', Never = 'never', } interface RenameAction { readonly oldUri: vscode.Uri; readonly newUri: vscode.Uri; readonly newFilePath: string; readonly oldFilePath: string; readonly jsTsFileThatIsBeingMoved: vscode.Uri; } class UpdateImportsOnFileRenameHandler extends Disposable { public static readonly minVersion = API.v300; private readonly _delayer = new Delayer(50); private readonly _pendingRenames = new Set<RenameAction>(); public constructor( private readonly client: ITypeScriptServiceClient, private readonly fileConfigurationManager: FileConfigurationManager, private readonly _handles: (uri: vscode.Uri) => Promise<boolean>, ) { super(); this._register(vscode.workspace.onDidRenameFiles(async (e) => { const [{ newUri, oldUri }] = e.files; const newFilePath = this.client.toPath(newUri); if (!newFilePath) { return; } const oldFilePath = this.client.toPath(oldUri); if (!oldFilePath) { return; } const config = this.getConfiguration(newUri); const setting = config.get<UpdateImportsOnFileMoveSetting>(updateImportsOnFileMoveName); if (setting === UpdateImportsOnFileMoveSetting.Never) { return; } // Try to get a js/ts file that is being moved // For directory moves, this returns a js/ts file under the directory. const jsTsFileThatIsBeingMoved = await this.getJsTsFileBeingMoved(newUri); if (!jsTsFileThatIsBeingMoved || !this.client.toPath(jsTsFileThatIsBeingMoved)) { return; } this._pendingRenames.add({ oldUri, newUri, newFilePath, oldFilePath, jsTsFileThatIsBeingMoved }); this._delayer.trigger(() => { vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: localize('renameProgress.title', "Checking for update of JS/TS imports") }, () => this.flushRenames()); }); })); } private async flushRenames(): Promise<void> { const renames = Array.from(this._pendingRenames); this._pendingRenames.clear(); for (const group of this.groupRenames(renames)) { const edits = new vscode.WorkspaceEdit(); const resourcesBeingRenamed: vscode.Uri[] = []; for (const { oldUri, newUri, newFilePath, oldFilePath, jsTsFileThatIsBeingMoved } of group) { const document = await vscode.workspace.openTextDocument(jsTsFileThatIsBeingMoved); // Make sure TS knows about file this.client.bufferSyncSupport.closeResource(oldUri); this.client.bufferSyncSupport.openTextDocument(document); if (await this.withEditsForFileRename(edits, document, oldFilePath, newFilePath)) { resourcesBeingRenamed.push(newUri); } } if (edits.size) { if (await this.confirmActionWithUser(resourcesBeingRenamed)) { await vscode.workspace.applyEdit(edits); } } } } private async confirmActionWithUser(newResources: readonly vscode.Uri[]): Promise<boolean> { if (!newResources.length) { return false; } const config = this.getConfiguration(newResources[0]); const setting = config.get<UpdateImportsOnFileMoveSetting>(updateImportsOnFileMoveName); switch (setting) { case UpdateImportsOnFileMoveSetting.Always: return true; case UpdateImportsOnFileMoveSetting.Never: return false; case UpdateImportsOnFileMoveSetting.Prompt: default: return this.promptUser(newResources); } } private getConfiguration(resource: vscode.Uri) { return vscode.workspace.getConfiguration(doesResourceLookLikeATypeScriptFile(resource) ? 'typescript' : 'javascript', resource); } private async promptUser(newResources: readonly vscode.Uri[]): Promise<boolean> { if (!newResources.length) { return false; } const enum Choice { None = 0, Accept = 1, Reject = 2, Always = 3, Never = 4, } interface Item extends vscode.MessageItem { readonly choice: Choice; } const response = await vscode.window.showInformationMessage<Item>( newResources.length === 1 ? localize('prompt', "Update imports for '{0}'?", path.basename(newResources[0].fsPath)) : this.getConfirmMessage(localize('promptMoreThanOne', "Update imports for the following {0} files?", newResources.length), newResources), { modal: true, }, { title: localize('reject.title', "No"), choice: Choice.Reject, isCloseAffordance: true, }, { title: localize('accept.title', "Yes"), choice: Choice.Accept, }, { title: localize('always.title', "Always automatically update imports"), choice: Choice.Always, }, { title: localize('never.title', "Never automatically update imports"), choice: Choice.Never, }); if (!response) { return false; } switch (response.choice) { case Choice.Accept: { return true; } case Choice.Reject: { return false; } case Choice.Always: { const config = this.getConfiguration(newResources[0]); config.update( updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Always, vscode.ConfigurationTarget.Global); return true; } case Choice.Never: { const config = this.getConfiguration(newResources[0]); config.update( updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Never, vscode.ConfigurationTarget.Global); return false; } } return false; } private async getJsTsFileBeingMoved(resource: vscode.Uri): Promise<vscode.Uri | undefined> { if (resource.scheme !== fileSchemes.file) { return undefined; } if (await isDirectory(resource)) { const files = await vscode.workspace.findFiles({ base: resource.fsPath, pattern: '**/*.{ts,tsx,js,jsx}', }, '**/node_modules/**', 1); return files[0]; } return (await this._handles(resource)) ? resource : undefined; } private async withEditsForFileRename( edits: vscode.WorkspaceEdit, document: vscode.TextDocument, oldFilePath: string, newFilePath: string, ): Promise<boolean> { const response = await this.client.interruptGetErr(() => { this.fileConfigurationManager.setGlobalConfigurationFromDocument(document, nulToken); const args: Proto.GetEditsForFileRenameRequestArgs = { oldFilePath, newFilePath, }; return this.client.execute('getEditsForFileRename', args, nulToken); }); if (response.type !== 'response' || !response.body.length) { return false; } typeConverters.WorkspaceEdit.withFileCodeEdits(edits, this.client, response.body); return true; } private groupRenames(renames: Iterable<RenameAction>): Iterable<Iterable<RenameAction>> { const groups = new Map<string, Set<RenameAction>>(); for (const rename of renames) { // Group renames by type (js/ts) and by workspace. const key = `${this.client.getWorkspaceRootForResource(rename.jsTsFileThatIsBeingMoved)}@@@${doesResourceLookLikeATypeScriptFile(rename.jsTsFileThatIsBeingMoved)}`; if (!groups.has(key)) { groups.set(key, new Set()); } groups.get(key)!.add(rename); } return groups.values(); } private getConfirmMessage(start: string, resourcesToConfirm: readonly vscode.Uri[]): string { const MAX_CONFIRM_FILES = 10; const paths = [start]; paths.push(''); paths.push(...resourcesToConfirm.slice(0, MAX_CONFIRM_FILES).map(r => path.basename(r.fsPath))); if (resourcesToConfirm.length > MAX_CONFIRM_FILES) { if (resourcesToConfirm.length - MAX_CONFIRM_FILES === 1) { paths.push(localize('moreFile', "...1 additional file not shown")); } else { paths.push(localize('moreFiles', "...{0} additional files not shown", resourcesToConfirm.length - MAX_CONFIRM_FILES)); } } paths.push(''); return paths.join('\n'); } } export function register( client: ITypeScriptServiceClient, fileConfigurationManager: FileConfigurationManager, handles: (uri: vscode.Uri) => Promise<boolean>, ) { return conditionalRegistration([ requireMinVersion(client, UpdateImportsOnFileRenameHandler.minVersion), requireSomeCapability(client, ClientCapability.Semantic), ], () => { return new UpdateImportsOnFileRenameHandler(client, fileConfigurationManager, handles); }); }
extensions/typescript-language-features/src/languageFeatures/updatePathsOnRename.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0007473977166227996, 0.00019217637600377202, 0.00016296451212838292, 0.00017376220785081387, 0.00010141137317987159 ]
{ "id": 5, "code_window": [ "\t\t});\n", "\t}\n", "\n", "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService): void {\n", "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService, logService: ILogService): void {\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { mark } from 'vs/base/common/performance'; import { domContentLoaded, addDisposableListener, EventType, EventHelper, detectFullscreen, addDisposableThrottledListener } from 'vs/base/browser/dom'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService, ConsoleLogService, MultiplexLogService, getLogLevel } from 'vs/platform/log/common/log'; import { ConsoleLogInAutomationService } from 'vs/platform/log/browser/log'; import { Disposable } from 'vs/base/common/lifecycle'; import { BrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { Workbench } from 'vs/workbench/browser/workbench'; import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IProductService } from 'vs/platform/product/common/productService'; import product from 'vs/platform/product/common/product'; import { RemoteAgentService } from 'vs/workbench/services/remote/browser/remoteAgentServiceImpl'; import { RemoteAuthorityResolverService } from 'vs/platform/remote/browser/remoteAuthorityResolverService'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { IFileService, IFileSystemProvider } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { Schemas } from 'vs/base/common/network'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { onUnexpectedError } from 'vs/base/common/errors'; import { setFullscreen } from 'vs/base/browser/browser'; import { isIOS, isMacintosh } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { IWorkspaceInitializationPayload } from 'vs/platform/workspaces/common/workspaces'; import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService'; import { ConfigurationCache } from 'vs/workbench/services/configuration/browser/configurationCache'; import { ISignService } from 'vs/platform/sign/common/sign'; import { SignService } from 'vs/platform/sign/browser/signService'; import type { IWorkbenchConstructionOptions, IWorkspace, IWorkbench } from 'vs/workbench/workbench.web.api'; import { BrowserStorageService } from 'vs/platform/storage/browser/storageService'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { registerWindowDriver } from 'vs/platform/driver/browser/driver'; import { BufferLogService } from 'vs/platform/log/common/bufferLog'; import { FileLogService } from 'vs/platform/log/common/fileLogService'; import { toLocalISOString } from 'vs/base/common/date'; import { isWorkspaceToOpen, isFolderToOpen } from 'vs/platform/windows/common/windows'; import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces'; import { coalesce } from 'vs/base/common/arrays'; import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider'; import { WebResourceIdentityService, IResourceIdentityService } from 'vs/platform/resource/common/resourceIdentityService'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IndexedDB, INDEXEDDB_LOGS_OBJECT_STORE, INDEXEDDB_USERDATA_OBJECT_STORE } from 'vs/platform/files/browser/indexedDBFileSystemProvider'; import { BrowserRequestService } from 'vs/workbench/services/request/browser/requestService'; import { IRequestService } from 'vs/platform/request/common/request'; import { IUserDataInitializationService, UserDataInitializationService } from 'vs/workbench/services/userData/browser/userDataInit'; import { UserDataSyncStoreManagementService } from 'vs/platform/userDataSync/common/userDataSyncStoreService'; import { IUserDataSyncStoreManagementService } from 'vs/platform/userDataSync/common/userDataSync'; class BrowserMain extends Disposable { constructor( private readonly domElement: HTMLElement, private readonly configuration: IWorkbenchConstructionOptions ) { super(); this.init(); } private init(): void { // Browser config setFullscreen(!!detectFullscreen()); } async open(): Promise<IWorkbench> { const services = await this.initServices(); await domContentLoaded(); mark('willStartWorkbench'); // Create Workbench const workbench = new Workbench( this.domElement, services.serviceCollection, services.logService ); // Listeners this.registerListeners(workbench, services.storageService); // Driver if (this.configuration.driver) { (async () => this._register(await registerWindowDriver()))(); } // Startup const instantiationService = workbench.startup(); // Return API Facade return instantiationService.invokeFunction(accessor => { const commandService = accessor.get(ICommandService); return { commands: { executeCommand: (command, ...args) => commandService.executeCommand(command, ...args) } }; }); } private registerListeners(workbench: Workbench, storageService: BrowserStorageService): void { // Layout const viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */; this._register(addDisposableListener(viewport, EventType.RESIZE, () => workbench.layout())); // Prevent the back/forward gestures in macOS this._register(addDisposableListener(this.domElement, EventType.WHEEL, e => e.preventDefault(), { passive: false })); // Prevent native context menus in web this._register(addDisposableListener(this.domElement, EventType.CONTEXT_MENU, e => EventHelper.stop(e, true))); // Prevent default navigation on drop this._register(addDisposableListener(this.domElement, EventType.DROP, e => EventHelper.stop(e, true))); // Workbench Lifecycle this._register(workbench.onBeforeShutdown(event => { if (storageService.hasPendingUpdate) { console.warn('Unload prevented: pending storage update'); event.veto(true); // prevent data loss from pending storage update } })); this._register(workbench.onWillShutdown(() => { storageService.close(); })); this._register(workbench.onShutdown(() => this.dispose())); // Fullscreen (Browser) [EventType.FULLSCREEN_CHANGE, EventType.WK_FULLSCREEN_CHANGE].forEach(event => { this._register(addDisposableListener(document, event, () => setFullscreen(!!detectFullscreen()))); }); // Fullscreen (Native) this._register(addDisposableThrottledListener(viewport, EventType.RESIZE, () => { setFullscreen(!!detectFullscreen()); }, undefined, isMacintosh ? 2000 /* adjust for macOS animation */ : 800 /* can be throttled */)); } private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: BrowserStorageService }> { const serviceCollection = new ServiceCollection(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: DO NOT ADD ANY OTHER SERVICE INTO THE COLLECTION HERE. // CONTRIBUTE IT VIA WORKBENCH.WEB.MAIN.TS AND registerSingleton(). // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Resource Identity const resourceIdentityService = this._register(new WebResourceIdentityService()); serviceCollection.set(IResourceIdentityService, resourceIdentityService); const payload = await this.resolveWorkspaceInitializationPayload(resourceIdentityService); // Product const productService: IProductService = { _serviceBrand: undefined, ...product, ...this.configuration.productConfiguration }; serviceCollection.set(IProductService, productService); // Environment const logsPath = URI.file(toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')).with({ scheme: 'vscode-log' }); const environmentService = new BrowserWorkbenchEnvironmentService({ workspaceId: payload.id, logsPath, ...this.configuration }, productService); serviceCollection.set(IWorkbenchEnvironmentService, environmentService); // Log const logService = new BufferLogService(getLogLevel(environmentService)); serviceCollection.set(ILogService, logService); // Remote const remoteAuthorityResolverService = new RemoteAuthorityResolverService(this.configuration.resourceUriProvider); serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService); // Signing const signService = new SignService(environmentService.options.connectionToken || this.getCookieValue('vscode-tkn')); serviceCollection.set(ISignService, signService); // Remote Agent const remoteAgentService = this._register(new RemoteAgentService(this.configuration.webSocketFactory, environmentService, productService, remoteAuthorityResolverService, signService, logService)); serviceCollection.set(IRemoteAgentService, remoteAgentService); // Files const fileService = this._register(new FileService(logService)); serviceCollection.set(IFileService, fileService); await this.registerFileSystemProviders(environmentService, fileService, remoteAgentService, logService, logsPath); // Long running services (workspace, config, storage) const [configurationService, storageService] = await Promise.all([ this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, logService).then(service => { // Workspace serviceCollection.set(IWorkspaceContextService, service); // Configuration serviceCollection.set(IConfigurationService, service); return service; }), this.createStorageService(payload, environmentService, fileService, logService).then(service => { // Storage serviceCollection.set(IStorageService, service); return service; }) ]); // Request Service const requestService = new BrowserRequestService(remoteAgentService, configurationService, logService); serviceCollection.set(IRequestService, requestService); // Userdata Sync Store Management Service const userDataSyncStoreManagementService = new UserDataSyncStoreManagementService(productService, configurationService, storageService); serviceCollection.set(IUserDataSyncStoreManagementService, userDataSyncStoreManagementService); // Userdata Initialize Service const userDataInitializationService = new UserDataInitializationService(environmentService, userDataSyncStoreManagementService, fileService, storageService, productService, requestService, logService); serviceCollection.set(IUserDataInitializationService, userDataInitializationService); if (await userDataInitializationService.requiresInitialization()) { mark('willInitRequiredUserData'); // Initialize required resources - settings & global state await userDataInitializationService.initializeRequiredResources(); // Important: Reload only local user configuration after initializing // Reloading complete configuraiton blocks workbench until remote configuration is loaded. await configurationService.reloadLocalUserConfiguration(); mark('didInitRequiredUserData'); } return { serviceCollection, logService, storageService }; } private async registerFileSystemProviders(environmentService: IWorkbenchEnvironmentService, fileService: IFileService, remoteAgentService: IRemoteAgentService, logService: BufferLogService, logsPath: URI): Promise<void> { const indexedDB = new IndexedDB(); // Logger (async () => { let indexedDBLogProvider: IFileSystemProvider | null = null; try { indexedDBLogProvider = await indexedDB.createFileSystemProvider(logsPath.scheme, INDEXEDDB_LOGS_OBJECT_STORE); } catch (error) { console.error(error); } if (indexedDBLogProvider) { fileService.registerProvider(logsPath.scheme, indexedDBLogProvider); } else { fileService.registerProvider(logsPath.scheme, new InMemoryFileSystemProvider()); } logService.logger = new MultiplexLogService(coalesce([ new ConsoleLogService(logService.getLevel()), new FileLogService('window', environmentService.logFile, logService.getLevel(), fileService), // Extension development test CLI: forward everything to test runner environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI ? new ConsoleLogInAutomationService(logService.getLevel()) : undefined ])); })(); const connection = remoteAgentService.getConnection(); if (connection) { // Remote file system const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService)); fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider); } // User data let indexedDBUserDataProvider: IFileSystemProvider | null = null; try { indexedDBUserDataProvider = await indexedDB.createFileSystemProvider(Schemas.userData, INDEXEDDB_USERDATA_OBJECT_STORE); } catch (error) { console.error(error); } fileService.registerProvider(Schemas.userData, indexedDBUserDataProvider || new InMemoryFileSystemProvider()); } private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: IWorkbenchEnvironmentService, fileService: IFileService, logService: ILogService): Promise<BrowserStorageService> { const storageService = new BrowserStorageService(environmentService, fileService); try { await storageService.initialize(payload); return storageService; } catch (error) { onUnexpectedError(error); logService.error(error); return storageService; } } private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: IWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, logService: ILogService): Promise<WorkspaceService> { const workspaceService = new WorkspaceService({ remoteAuthority: this.configuration.remoteAuthority, configurationCache: new ConfigurationCache() }, environmentService, fileService, remoteAgentService, logService); try { await workspaceService.initialize(payload); return workspaceService; } catch (error) { onUnexpectedError(error); logService.error(error); return workspaceService; } } private async resolveWorkspaceInitializationPayload(resourceIdentityService: IResourceIdentityService): Promise<IWorkspaceInitializationPayload> { let workspace: IWorkspace | undefined = undefined; if (this.configuration.workspaceProvider) { workspace = this.configuration.workspaceProvider.workspace; } // Multi-root workspace if (workspace && isWorkspaceToOpen(workspace)) { return getWorkspaceIdentifier(workspace.workspaceUri); } // Single-folder workspace if (workspace && isFolderToOpen(workspace)) { const id = await resourceIdentityService.resolveResourceIdentity(workspace.folderUri); return { id, folder: workspace.folderUri }; } return { id: 'empty-window' }; } private getCookieValue(name: string): string | undefined { const match = document.cookie.match('(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)'); // See https://stackoverflow.com/a/25490531 return match ? match.pop() : undefined; } } export function main(domElement: HTMLElement, options: IWorkbenchConstructionOptions): Promise<IWorkbench> { const workbench = new BrowserMain(domElement, options); return workbench.open(); }
src/vs/workbench/browser/web.main.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.9981424808502197, 0.08626750111579895, 0.0001633316423976794, 0.0001729464711388573, 0.2790922224521637 ]
{ "id": 5, "code_window": [ "\t\t});\n", "\t}\n", "\n", "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService): void {\n", "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService, logService: ILogService): void {\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export class IdGenerator { private _prefix: string; private _lastId: number; constructor(prefix: string) { this._prefix = prefix; this._lastId = 0; } public nextId(): string { return this._prefix + (++this._lastId); } } export const defaultGenerator = new IdGenerator('id#');
src/vs/base/common/idGenerator.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017735152505338192, 0.0001740644220262766, 0.00016930417041294277, 0.00017553757061250508, 0.0000034465060707589146 ]
{ "id": 5, "code_window": [ "\t\t});\n", "\t}\n", "\n", "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService): void {\n", "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService, logService: ILogService): void {\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------- The base color for this template is #5c87b2. If you'd like to use a different color start by replacing all instances of #5c87b2 with your new color. ----------------------------------------------------------*/ body { background-color: #5c87b2; font-size: .75em; font-family: Segoe UI, Verdana, Helvetica, Sans-Serif; margin: 8px; padding: 0; color: #696969; } h1, h2, h3, h4, h5, h6 { color: #000; font-size: 40px; margin: 0px; } textarea { font-family: Consolas } #results { margin-top: 2em; margin-left: 2em; color: black; font-size: medium; }
src/vs/workbench/services/textfile/test/node/encoding/fixtures/some_ansi.css
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017831125296652317, 0.00017586737521924078, 0.00017380794452037662, 0.00017610503709875047, 0.0000015764854879307677 ]
{ "id": 5, "code_window": [ "\t\t});\n", "\t}\n", "\n", "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService): void {\n", "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate registerListeners(workbench: Workbench, storageService: BrowserStorageService, logService: ILogService): void {\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { IKeyMods, IQuickPickSeparator, IQuickInputService, IQuickPick } from 'vs/platform/quickinput/common/quickInput'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { IRange } from 'vs/editor/common/core/range'; import { Registry } from 'vs/platform/registry/common/platform'; import { IQuickAccessRegistry, Extensions as QuickaccessExtensions } from 'vs/platform/quickinput/common/quickAccess'; import { AbstractGotoSymbolQuickAccessProvider, IGotoSymbolQuickPickItem } from 'vs/editor/contrib/quickAccess/gotoSymbolQuickAccess'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkbenchEditorConfiguration, IEditorPane } from 'vs/workbench/common/editor'; import { ITextModel } from 'vs/editor/common/model'; import { DisposableStore, IDisposable, toDisposable, Disposable } from 'vs/base/common/lifecycle'; import { timeout } from 'vs/base/common/async'; import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation'; import { registerAction2, Action2 } from 'vs/platform/actions/common/actions'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { prepareQuery } from 'vs/base/common/fuzzyScorer'; import { SymbolKind } from 'vs/editor/common/modes'; import { fuzzyScore, createMatches } from 'vs/base/common/filters'; import { onUnexpectedError } from 'vs/base/common/errors'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; export class GotoSymbolQuickAccessProvider extends AbstractGotoSymbolQuickAccessProvider { protected readonly onDidActiveTextEditorControlChange = this.editorService.onDidActiveEditorChange; constructor( @IEditorService private readonly editorService: IEditorService, @IConfigurationService private readonly configurationService: IConfigurationService ) { super({ openSideBySideDirection: () => this.configuration.openSideBySideDirection }); } //#region DocumentSymbols (text editor required) protected provideWithTextEditor(editor: IEditor, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { if (this.canPickFromTableOfContents()) { return this.doGetTableOfContentsPicks(picker); } return super.provideWithTextEditor(editor, picker, token); } private get configuration() { const editorConfig = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench.editor; return { openEditorPinned: !editorConfig.enablePreviewFromQuickOpen, openSideBySideDirection: editorConfig.openSideBySideDirection }; } protected get activeTextEditorControl() { return this.editorService.activeTextEditorControl; } protected gotoLocation(editor: IEditor, options: { range: IRange, keyMods: IKeyMods, forceSideBySide?: boolean, preserveFocus?: boolean }): void { // Check for sideBySide use if ((options.keyMods.ctrlCmd || options.forceSideBySide) && this.editorService.activeEditor) { this.editorService.openEditor(this.editorService.activeEditor, { selection: options.range, pinned: options.keyMods.alt || this.configuration.openEditorPinned, preserveFocus: options.preserveFocus }, SIDE_GROUP); } // Otherwise let parent handle it else { super.gotoLocation(editor, options); } } //#endregion //#region public methods to use this picker from other pickers private static readonly SYMBOL_PICKS_TIMEOUT = 8000; async getSymbolPicks(model: ITextModel, filter: string, options: { extraContainerLabel?: string }, disposables: DisposableStore, token: CancellationToken): Promise<Array<IGotoSymbolQuickPickItem | IQuickPickSeparator>> { // If the registry does not know the model, we wait for as long as // the registry knows it. This helps in cases where a language // registry was not activated yet for providing any symbols. // To not wait forever, we eventually timeout though. const result = await Promise.race([ this.waitForLanguageSymbolRegistry(model, disposables), timeout(GotoSymbolQuickAccessProvider.SYMBOL_PICKS_TIMEOUT) ]); if (!result || token.isCancellationRequested) { return []; } return this.doGetSymbolPicks(this.getDocumentSymbols(model, true, token), prepareQuery(filter), options, token); } addDecorations(editor: IEditor, range: IRange): void { super.addDecorations(editor, range); } clearDecorations(editor: IEditor): void { super.clearDecorations(editor); } //#endregion protected provideWithoutTextEditor(picker: IQuickPick<IGotoSymbolQuickPickItem>): IDisposable { if (this.canPickFromTableOfContents()) { return this.doGetTableOfContentsPicks(picker); } return super.provideWithoutTextEditor(picker); } private canPickFromTableOfContents(): boolean { return this.editorService.activeEditorPane ? TableOfContentsProviderRegistry.has(this.editorService.activeEditorPane.getId()) : false; } private doGetTableOfContentsPicks(picker: IQuickPick<IGotoSymbolQuickPickItem>): IDisposable { const pane = this.editorService.activeEditorPane; if (!pane) { return Disposable.None; } const provider = TableOfContentsProviderRegistry.get(pane.getId())!; const cts = new CancellationTokenSource(); const disposables = new DisposableStore(); disposables.add(toDisposable(() => cts.dispose(true))); picker.busy = true; provider.provideTableOfContents(pane, { disposables }, cts.token).then(entries => { picker.busy = false; if (cts.token.isCancellationRequested || !entries || entries.length === 0) { return; } const items: IGotoSymbolQuickPickItem[] = entries.map((entry, idx) => { return { kind: SymbolKind.File, index: idx, score: 0, label: entry.icon ? `$(${entry.icon.id}) ${entry.label}` : entry.label, ariaLabel: entry.detail ? `${entry.label}, ${entry.detail}` : entry.label, detail: entry.detail, description: entry.description, }; }); disposables.add(picker.onDidAccept(() => { picker.hide(); const [entry] = picker.selectedItems; entries[entry.index]?.pick(); })); const updatePickerItems = () => { const filteredItems = items.filter(item => { if (picker.value === '@') { // default, no filtering, scoring... item.score = 0; item.highlights = undefined; return true; } const score = fuzzyScore(picker.value, picker.value.toLowerCase(), 1 /*@-character*/, item.label, item.label.toLowerCase(), 0, true); if (!score) { return false; } item.score = score[1]; item.highlights = { label: createMatches(score) }; return true; }); if (filteredItems.length === 0) { const label = localize('empty', 'No matching entries'); picker.items = [{ label, index: -1, kind: SymbolKind.String }]; picker.ariaLabel = label; } else { picker.items = filteredItems; } }; updatePickerItems(); disposables.add(picker.onDidChangeValue(updatePickerItems)); disposables.add(picker.onDidChangeActive(() => { const [entry] = picker.activeItems; if (entry) { entries[entry.index]?.preview(); } })); }).catch(err => { onUnexpectedError(err); picker.hide(); }); return disposables; } } Registry.as<IQuickAccessRegistry>(QuickaccessExtensions.Quickaccess).registerQuickAccessProvider({ ctor: GotoSymbolQuickAccessProvider, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX, contextKey: 'inFileSymbolsPicker', placeholder: localize('gotoSymbolQuickAccessPlaceholder', "Type the name of a symbol to go to."), helpEntries: [ { description: localize('gotoSymbolQuickAccess', "Go to Symbol in Editor"), prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX, needsEditor: true }, { description: localize('gotoSymbolByCategoryQuickAccess', "Go to Symbol in Editor by Category"), prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY, needsEditor: true } ] }); registerAction2(class GotoSymbolAction extends Action2 { constructor() { super({ id: 'workbench.action.gotoSymbol', title: { value: localize('gotoSymbol', "Go to Symbol in Editor..."), original: 'Go to Symbol in Editor...' }, f1: true, keybinding: { when: undefined, weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_O } }); } run(accessor: ServicesAccessor) { accessor.get(IQuickInputService).quickAccess.show(GotoSymbolQuickAccessProvider.PREFIX); } }); //#region toc definition and logic export interface ITableOfContentsEntry { icon?: ThemeIcon; label: string; detail?: string; description?: string; pick(): any; preview(): any; } export interface ITableOfContentsProvider<T extends IEditorPane = IEditorPane> { provideTableOfContents(editor: T, context: { disposables: DisposableStore }, token: CancellationToken): Promise<ITableOfContentsEntry[] | undefined | null>; } class ProviderRegistry { private readonly _provider = new Map<string, ITableOfContentsProvider>(); register(type: string, provider: ITableOfContentsProvider): IDisposable { this._provider.set(type, provider); return toDisposable(() => { if (this._provider.get(type) === provider) { this._provider.delete(type); } }); } get(type: string): ITableOfContentsProvider | undefined { return this._provider.get(type); } has(type: string): boolean { return this._provider.has(type); } } export const TableOfContentsProviderRegistry = new ProviderRegistry(); //#endregion
src/vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0001774337433744222, 0.00017240212764590979, 0.00016286602476611733, 0.00017265665519516915, 0.000004166141025052639 ]
{ "id": 6, "code_window": [ "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n", "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => workbench.layout()));\n", "\n", "\t\t// Prevent the back/forward gestures in macOS\n", "\t\tthis._register(addDisposableListener(this.domElement, EventType.WHEEL, e => e.preventDefault(), { passive: false }));\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => {\n", "\t\t\tlogService.trace(`web.main#${isIOS && window.visualViewport ? 'visualViewport' : 'window'}Resize`);\n", "\t\t\tworkbench.layout();\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; import { EventType, addDisposableListener, isAncestor, getClientArea, Dimension, position, size, IDimension } from 'vs/base/browser/dom'; import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { Registry } from 'vs/platform/registry/common/platform'; import { isWindows, isLinux, isMacintosh, isWeb, isNative } from 'vs/base/common/platform'; import { pathsToEditors, SideBySideEditorInput } from 'vs/workbench/common/editor'; import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart'; import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart'; import { PanelRegistry, Extensions as PanelExtensions } from 'vs/workbench/browser/panel'; import { Position, Parts, PanelOpensMaximizedOptions, IWorkbenchLayoutService, positionFromString, positionToString, panelOpensMaximizedFromString } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IStorageService, StorageScope, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { LifecyclePhase, StartupKind, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility, IPath } from 'vs/platform/windows/common/windows'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IEditor } from 'vs/editor/common/editorCommon'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { Part } from 'vs/workbench/browser/part'; import { IStatusbarService } from 'vs/workbench/services/statusbar/common/statusbar'; import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService'; import { IFileService } from 'vs/platform/files/common/files'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { coalesce } from 'vs/base/common/arrays'; import { assertIsDefined } from 'vs/base/common/types'; import { INotificationService, NotificationsFilter } from 'vs/platform/notification/common/notification'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from 'vs/workbench/common/theme'; import { LineNumbersType } from 'vs/editor/common/config/editorOptions'; import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart'; import { URI } from 'vs/base/common/uri'; import { IViewDescriptorService, ViewContainerLocation, IViewsService } from 'vs/workbench/common/views'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { mark } from 'vs/base/common/performance'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; export enum Settings { ACTIVITYBAR_VISIBLE = 'workbench.activityBar.visible', STATUSBAR_VISIBLE = 'workbench.statusBar.visible', SIDEBAR_POSITION = 'workbench.sideBar.location', PANEL_POSITION = 'workbench.panel.defaultLocation', PANEL_OPENS_MAXIMIZED = 'workbench.panel.opensMaximized', ZEN_MODE_RESTORE = 'zenMode.restore', } enum Storage { SIDEBAR_HIDDEN = 'workbench.sidebar.hidden', SIDEBAR_SIZE = 'workbench.sidebar.size', PANEL_HIDDEN = 'workbench.panel.hidden', PANEL_POSITION = 'workbench.panel.location', PANEL_SIZE = 'workbench.panel.size', PANEL_DIMENSION = 'workbench.panel.dimension', PANEL_LAST_NON_MAXIMIZED_WIDTH = 'workbench.panel.lastNonMaximizedWidth', PANEL_LAST_NON_MAXIMIZED_HEIGHT = 'workbench.panel.lastNonMaximizedHeight', PANEL_LAST_IS_MAXIMIZED = 'workbench.panel.lastIsMaximized', EDITOR_HIDDEN = 'workbench.editor.hidden', ZEN_MODE_ENABLED = 'workbench.zenmode.active', CENTERED_LAYOUT_ENABLED = 'workbench.centerededitorlayout.active', GRID_LAYOUT = 'workbench.grid.layout', GRID_WIDTH = 'workbench.grid.width', GRID_HEIGHT = 'workbench.grid.height' } enum Classes { SIDEBAR_HIDDEN = 'nosidebar', EDITOR_HIDDEN = 'noeditorarea', PANEL_HIDDEN = 'nopanel', STATUSBAR_HIDDEN = 'nostatusbar', FULLSCREEN = 'fullscreen', WINDOW_BORDER = 'border' } interface PanelActivityState { id: string; name?: string; pinned: boolean; order: number; visible: boolean; } interface SideBarActivityState { id: string; pinned: boolean; order: number; visible: boolean; } export abstract class Layout extends Disposable implements IWorkbenchLayoutService { declare readonly _serviceBrand: undefined; //#region Events private readonly _onZenModeChange = this._register(new Emitter<boolean>()); readonly onZenModeChange = this._onZenModeChange.event; private readonly _onFullscreenChange = this._register(new Emitter<boolean>()); readonly onFullscreenChange = this._onFullscreenChange.event; private readonly _onCenteredLayoutChange = this._register(new Emitter<boolean>()); readonly onCenteredLayoutChange = this._onCenteredLayoutChange.event; private readonly _onMaximizeChange = this._register(new Emitter<boolean>()); readonly onMaximizeChange = this._onMaximizeChange.event; private readonly _onPanelPositionChange = this._register(new Emitter<string>()); readonly onPanelPositionChange = this._onPanelPositionChange.event; private readonly _onPartVisibilityChange = this._register(new Emitter<void>()); readonly onPartVisibilityChange = this._onPartVisibilityChange.event; private readonly _onLayout = this._register(new Emitter<IDimension>()); readonly onLayout = this._onLayout.event; //#endregion readonly container: HTMLElement = document.createElement('div'); private _dimension!: IDimension; get dimension(): IDimension { return this._dimension; } get offset() { return { top: (() => { let offset = 0; if (this.isVisible(Parts.TITLEBAR_PART)) { offset = this.getPart(Parts.TITLEBAR_PART).maximumHeight; } return offset; })() }; } private readonly parts = new Map<string, Part>(); private workbenchGrid!: SerializableGrid<ISerializableView>; private disposed: boolean | undefined; private titleBarPartView!: ISerializableView; private activityBarPartView!: ISerializableView; private sideBarPartView!: ISerializableView; private panelPartView!: ISerializableView; private editorPartView!: ISerializableView; private statusBarPartView!: ISerializableView; private environmentService!: IWorkbenchEnvironmentService; private extensionService!: IExtensionService; private configurationService!: IConfigurationService; private lifecycleService!: ILifecycleService; private storageService!: IStorageService; private hostService!: IHostService; private editorService!: IEditorService; private editorGroupService!: IEditorGroupsService; private panelService!: IPanelService; private titleService!: ITitleService; private viewletService!: IViewletService; private viewDescriptorService!: IViewDescriptorService; private viewsService!: IViewsService; private contextService!: IWorkspaceContextService; private backupFileService!: IBackupFileService; private notificationService!: INotificationService; private themeService!: IThemeService; private activityBarService!: IActivityBarService; private statusBarService!: IStatusbarService; protected readonly state = { fullscreen: false, maximized: false, hasFocus: false, windowBorder: false, menuBar: { visibility: 'default' as MenuBarVisibility, toggled: false }, activityBar: { hidden: false }, sideBar: { hidden: false, position: Position.LEFT, width: 300, viewletToRestore: undefined as string | undefined }, editor: { hidden: false, centered: false, restoreCentered: false, restoreEditors: false, editorsToOpen: [] as Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] }, panel: { hidden: false, position: Position.BOTTOM, lastNonMaximizedWidth: 300, lastNonMaximizedHeight: 300, wasLastMaximized: false, panelToRestore: undefined as string | undefined }, statusBar: { hidden: false }, views: { defaults: undefined as (string[] | undefined) }, zenMode: { active: false, restore: false, transitionedToFullScreen: false, transitionedToCenteredEditorLayout: false, wasSideBarVisible: false, wasPanelVisible: false, transitionDisposables: new DisposableStore(), setNotificationsFilter: false, editorWidgetSet: new Set<IEditor>() } }; constructor( protected readonly parent: HTMLElement ) { super(); } protected initLayout(accessor: ServicesAccessor): void { // Services this.environmentService = accessor.get(IWorkbenchEnvironmentService); this.configurationService = accessor.get(IConfigurationService); this.lifecycleService = accessor.get(ILifecycleService); this.hostService = accessor.get(IHostService); this.contextService = accessor.get(IWorkspaceContextService); this.storageService = accessor.get(IStorageService); this.backupFileService = accessor.get(IBackupFileService); this.themeService = accessor.get(IThemeService); this.extensionService = accessor.get(IExtensionService); // Parts this.editorService = accessor.get(IEditorService); this.editorGroupService = accessor.get(IEditorGroupsService); this.panelService = accessor.get(IPanelService); this.viewletService = accessor.get(IViewletService); this.viewDescriptorService = accessor.get(IViewDescriptorService); this.viewsService = accessor.get(IViewsService); this.titleService = accessor.get(ITitleService); this.notificationService = accessor.get(INotificationService); this.activityBarService = accessor.get(IActivityBarService); this.statusBarService = accessor.get(IStatusbarService); // Listeners this.registerLayoutListeners(); // State this.initLayoutState(accessor.get(ILifecycleService), accessor.get(IFileService)); } private registerLayoutListeners(): void { // Restore editor if hidden and it changes // The editor service will always trigger this // on startup so we can ignore the first one let firstTimeEditorActivation = true; const showEditorIfHidden = () => { if (!firstTimeEditorActivation && this.state.editor.hidden) { this.toggleMaximizedPanel(); } firstTimeEditorActivation = false; }; // Restore editor part on any editor change this._register(this.editorService.onDidVisibleEditorsChange(showEditorIfHidden)); this._register(this.editorGroupService.onDidActivateGroup(showEditorIfHidden)); // Revalidate center layout when active editor changes: diff editor quits centered mode. this._register(this.editorService.onDidActiveEditorChange(() => this.centerEditorLayout(this.state.editor.centered))); // Configuration changes this._register(this.configurationService.onDidChangeConfiguration(() => this.doUpdateLayoutConfiguration())); // Fullscreen changes this._register(onDidChangeFullscreen(() => this.onFullscreenChanged())); // Group changes this._register(this.editorGroupService.onDidAddGroup(() => this.centerEditorLayout(this.state.editor.centered))); this._register(this.editorGroupService.onDidRemoveGroup(() => this.centerEditorLayout(this.state.editor.centered))); // Prevent workbench from scrolling #55456 this._register(addDisposableListener(this.container, EventType.SCROLL, () => this.container.scrollTop = 0)); // Menubar visibility changes if ((isWindows || isLinux || isWeb) && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { this._register(this.titleService.onMenubarVisibilityChange(visible => this.onMenubarToggled(visible))); } // Theme changes this._register(this.themeService.onDidColorThemeChange(theme => this.updateStyles())); // Window focus changes this._register(this.hostService.onDidChangeFocus(e => this.onWindowFocusChanged(e))); } private onMenubarToggled(visible: boolean) { if (visible !== this.state.menuBar.toggled) { this.state.menuBar.toggled = visible; if (this.state.fullscreen && (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default')) { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.layout(); } } } private onFullscreenChanged(): void { this.state.fullscreen = isFullscreen(); // Apply as CSS class if (this.state.fullscreen) { this.container.classList.add(Classes.FULLSCREEN); } else { this.container.classList.remove(Classes.FULLSCREEN); if (this.state.zenMode.transitionedToFullScreen && this.state.zenMode.active) { this.toggleZenMode(); } } // Changing fullscreen state of the window has an impact on custom title bar visibility, so we need to update if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { // Propagate to grid this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); this.updateWindowBorder(true); this.layout(); // handle title bar when fullscreen changes } this._onFullscreenChange.fire(this.state.fullscreen); } private onWindowFocusChanged(hasFocus: boolean): void { if (this.state.hasFocus === hasFocus) { return; } this.state.hasFocus = hasFocus; this.updateWindowBorder(); } private doUpdateLayoutConfiguration(skipLayout?: boolean): void { // Sidebar position const newSidebarPositionValue = this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION); const newSidebarPosition = (newSidebarPositionValue === 'right') ? Position.RIGHT : Position.LEFT; if (newSidebarPosition !== this.getSideBarPosition()) { this.setSideBarPosition(newSidebarPosition); } // Panel position this.updatePanelPosition(); if (!this.state.zenMode.active) { // Statusbar visibility const newStatusbarHiddenValue = !this.configurationService.getValue<boolean>(Settings.STATUSBAR_VISIBLE); if (newStatusbarHiddenValue !== this.state.statusBar.hidden) { this.setStatusBarHidden(newStatusbarHiddenValue, skipLayout); } // Activitybar visibility const newActivityBarHiddenValue = !this.configurationService.getValue<boolean>(Settings.ACTIVITYBAR_VISIBLE); if (newActivityBarHiddenValue !== this.state.activityBar.hidden) { this.setActivityBarHidden(newActivityBarHiddenValue, skipLayout); } } // Menubar visibility const newMenubarVisibility = getMenuBarVisibility(this.configurationService, this.environmentService); this.setMenubarVisibility(newMenubarVisibility, !!skipLayout); // Centered Layout this.centerEditorLayout(this.state.editor.centered, skipLayout); } private setSideBarPosition(position: Position): void { const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const wasHidden = this.state.sideBar.hidden; const newPositionValue = (position === Position.LEFT) ? 'left' : 'right'; const oldPositionValue = (this.state.sideBar.position === Position.LEFT) ? 'left' : 'right'; this.state.sideBar.position = position; // Adjust CSS const activityBarContainer = assertIsDefined(activityBar.getContainer()); const sideBarContainer = assertIsDefined(sideBar.getContainer()); activityBarContainer.classList.remove(oldPositionValue); sideBarContainer.classList.remove(oldPositionValue); activityBarContainer.classList.add(newPositionValue); sideBarContainer.classList.add(newPositionValue); // Update Styles activityBar.updateStyles(); sideBar.updateStyles(); // Layout if (!wasHidden) { this.state.sideBar.width = this.workbenchGrid.getViewSize(this.sideBarPartView).width; } if (position === Position.LEFT) { this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 0]); this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 1]); } else { this.workbenchGrid.moveViewTo(this.sideBarPartView, [1, 4]); this.workbenchGrid.moveViewTo(this.activityBarPartView, [1, 4]); } this.layout(); } private updateWindowBorder(skipLayout: boolean = false) { if (isWeb || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } const theme = this.themeService.getColorTheme(); const activeBorder = theme.getColor(WINDOW_ACTIVE_BORDER); const inactiveBorder = theme.getColor(WINDOW_INACTIVE_BORDER); let windowBorder = false; if (!this.state.fullscreen && !this.state.maximized && (activeBorder || inactiveBorder)) { windowBorder = true; // If the inactive color is missing, fallback to the active one const borderColor = this.state.hasFocus ? activeBorder : inactiveBorder ?? activeBorder; this.container.style.setProperty('--window-border-color', borderColor?.toString() ?? 'transparent'); } if (windowBorder === this.state.windowBorder) { return; } this.state.windowBorder = windowBorder; this.container.classList.toggle(Classes.WINDOW_BORDER, windowBorder); if (!skipLayout) { this.layout(); } } private updateStyles() { this.updateWindowBorder(); } private initLayoutState(lifecycleService: ILifecycleService, fileService: IFileService): void { // Default Layout this.applyDefaultLayout(this.environmentService, this.storageService); // Fullscreen this.state.fullscreen = isFullscreen(); // Menubar visibility this.state.menuBar.visibility = getMenuBarVisibility(this.configurationService, this.environmentService); // Activity bar visibility this.state.activityBar.hidden = !this.configurationService.getValue<string>(Settings.ACTIVITYBAR_VISIBLE); // Sidebar visibility this.state.sideBar.hidden = this.storageService.getBoolean(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE, this.contextService.getWorkbenchState() === WorkbenchState.EMPTY); // Sidebar position this.state.sideBar.position = (this.configurationService.getValue<string>(Settings.SIDEBAR_POSITION) === 'right') ? Position.RIGHT : Position.LEFT; // Sidebar viewlet if (!this.state.sideBar.hidden) { // Only restore last viewlet if window was reloaded or we are in development mode let viewletToRestore: string | undefined; if (!this.environmentService.isBuilt || lifecycleService.startupKind === StartupKind.ReloadedWindow || isWeb) { viewletToRestore = this.storageService.get(SidebarPart.activeViewletSettingsKey, StorageScope.WORKSPACE, this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); } else { viewletToRestore = this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id; } if (viewletToRestore) { this.state.sideBar.viewletToRestore = viewletToRestore; } else { this.state.sideBar.hidden = true; // we hide sidebar if there is no viewlet to restore } } // Editor visibility this.state.editor.hidden = this.storageService.getBoolean(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE, false); // Editor centered layout this.state.editor.restoreCentered = this.storageService.getBoolean(Storage.CENTERED_LAYOUT_ENABLED, StorageScope.WORKSPACE, false); // Editors to open this.state.editor.editorsToOpen = this.resolveEditorsToOpen(fileService); // Panel visibility this.state.panel.hidden = this.storageService.getBoolean(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE, true); // Whether or not the panel was last maximized this.state.panel.wasLastMaximized = this.storageService.getBoolean(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE, false); // Panel position this.updatePanelPosition(); // Panel to restore if (!this.state.panel.hidden) { let panelToRestore = this.storageService.get(PanelPart.activePanelSettingsKey, StorageScope.WORKSPACE, Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); if (panelToRestore) { this.state.panel.panelToRestore = panelToRestore; } else { this.state.panel.hidden = true; // we hide panel if there is no panel to restore } } // Panel size before maximized this.state.panel.lastNonMaximizedHeight = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, StorageScope.GLOBAL, 300); this.state.panel.lastNonMaximizedWidth = this.storageService.getNumber(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, StorageScope.GLOBAL, 300); // Statusbar visibility this.state.statusBar.hidden = !this.configurationService.getValue<string>(Settings.STATUSBAR_VISIBLE); // Zen mode enablement this.state.zenMode.restore = this.storageService.getBoolean(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE, false) && this.configurationService.getValue(Settings.ZEN_MODE_RESTORE); this.state.hasFocus = this.hostService.hasFocus; // Window border this.updateWindowBorder(true); } private applyDefaultLayout(environmentService: IWorkbenchEnvironmentService, storageService: IStorageService) { const defaultLayout = environmentService.options?.defaultLayout; if (!defaultLayout) { return; } if (!storageService.isNew(StorageScope.WORKSPACE)) { return; } const { views } = defaultLayout; if (views?.length) { this.state.views.defaults = views.map(v => v.id); return; } // TODO@eamodio Everything below here is deprecated and will be removed once Codespaces migrates const { sidebar } = defaultLayout; if (sidebar) { if (sidebar.visible !== undefined) { if (sidebar.visible) { storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } else { storageService.store(Storage.SIDEBAR_HIDDEN, true, StorageScope.WORKSPACE); } } if (sidebar.containers?.length) { const sidebarState: SideBarActivityState[] = []; let order = -1; for (const container of sidebar.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let viewletId; switch (container.id) { case 'explorer': viewletId = 'workbench.view.explorer'; break; case 'run': viewletId = 'workbench.view.debug'; break; case 'scm': viewletId = 'workbench.view.scm'; break; case 'search': viewletId = 'workbench.view.search'; break; case 'extensions': viewletId = 'workbench.view.extensions'; break; case 'remote': viewletId = 'workbench.view.remote'; break; default: viewletId = `workbench.view.extension.${container.id}`; } if (container.active) { storageService.store(SidebarPart.activeViewletSettingsKey, viewletId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: SideBarActivityState = { id: viewletId, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; sidebarState.push(state); } if (container.views !== undefined) { const viewsState: { id: string, isHidden?: boolean, order?: number }[] = []; const viewsWorkspaceState: { [id: string]: { collapsed: boolean, isHidden?: boolean, size?: number } } = {}; for (const view of container.views) { if (view.order !== undefined || view.visible !== undefined) { viewsState.push({ id: view.id, isHidden: view.visible === undefined ? undefined : !view.visible, order: view.order === undefined ? undefined : view.order }); } if (view.collapsed !== undefined) { viewsWorkspaceState[view.id] = { collapsed: view.collapsed, isHidden: view.visible === undefined ? undefined : !view.visible, }; } } storageService.store(`${viewletId}.state.hidden`, JSON.stringify(viewsState), StorageScope.GLOBAL); storageService.store(`${viewletId}.state`, JSON.stringify(viewsWorkspaceState), StorageScope.WORKSPACE); } } if (sidebarState.length) { storageService.store(ActivitybarPart.PINNED_VIEW_CONTAINERS, JSON.stringify(sidebarState), StorageScope.GLOBAL); } } } const { panel } = defaultLayout; if (panel) { if (panel.visible !== undefined) { if (panel.visible) { storageService.store(Storage.PANEL_HIDDEN, false, StorageScope.WORKSPACE); } else { storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); } } if (panel.containers?.length) { const panelState: PanelActivityState[] = []; let order = -1; for (const container of panel.containers.sort((a, b) => (a.order ?? 1) - (b.order ?? 1))) { let name; let panelId = container.id; switch (panelId) { case 'terminal': name = 'Terminal'; panelId = 'workbench.panel.terminal'; break; case 'debug': name = 'Debug Console'; panelId = 'workbench.panel.repl'; break; case 'problems': name = 'Problems'; panelId = 'workbench.panel.markers'; break; case 'output': name = 'Output'; panelId = 'workbench.panel.output'; break; case 'comments': name = 'Comments'; panelId = 'workbench.panel.comments'; break; case 'refactor': name = 'Refactor Preview'; panelId = 'refactorPreview'; break; default: continue; } if (container.active) { storageService.store(PanelPart.activePanelSettingsKey, panelId, StorageScope.WORKSPACE); } if (container.order !== undefined || (container.active === undefined && container.visible !== undefined)) { order = container.order ?? (order + 1); const state: PanelActivityState = { id: panelId, name: name, order: order, pinned: (container.active || container.visible) ?? true, visible: (container.active || container.visible) ?? true }; panelState.push(state); } } if (panelState.length) { storageService.store(PanelPart.PINNED_PANELS, JSON.stringify(panelState), StorageScope.GLOBAL); } } } } private resolveEditorsToOpen(fileService: IFileService): Promise<IResourceEditorInputType[]> | IResourceEditorInputType[] { const initialFilesToOpen = this.getInitialFilesToOpen(); // Only restore editors if we are not instructed to open files initially this.state.editor.restoreEditors = initialFilesToOpen === undefined; // Files to open, diff or create if (initialFilesToOpen !== undefined) { // Files to diff is exclusive return pathsToEditors(initialFilesToOpen.filesToDiff, fileService).then(filesToDiff => { if (filesToDiff?.length === 2) { return [{ leftResource: filesToDiff[0].resource, rightResource: filesToDiff[1].resource, options: { pinned: true }, forceFile: true }]; } // Otherwise: Open/Create files return pathsToEditors(initialFilesToOpen.filesToOpenOrCreate, fileService); }); } // Empty workbench else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && this.configurationService.getValue('workbench.startupEditor') === 'newUntitledFile') { if (this.editorGroupService.willRestoreEditors) { return []; // do not open any empty untitled file if we restored editors from previous session } return this.backupFileService.hasBackups().then(hasBackups => { if (hasBackups) { return []; // do not open any empty untitled file if we have backups to restore } return [Object.create(null)]; // open empty untitled file }); } return []; } private _openedDefaultEditors: boolean = false; get openedDefaultEditors() { return this._openedDefaultEditors; } private getInitialFilesToOpen(): { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[] } | undefined { const defaultLayout = this.environmentService.options?.defaultLayout; if (defaultLayout?.editors?.length && this.storageService.isNew(StorageScope.WORKSPACE)) { this._openedDefaultEditors = true; return { filesToOpenOrCreate: defaultLayout.editors .map<IPath>(f => { // Support the old path+scheme api until embedders can migrate if ('path' in f && 'scheme' in f) { return { fileUri: URI.file((f as any).path).with({ scheme: (f as any).scheme }) }; } return { fileUri: URI.revive(f.uri), openOnlyIfExists: f.openOnlyIfExists, overrideId: f.openWith }; }) }; } const { filesToOpenOrCreate, filesToDiff } = this.environmentService.configuration; if (filesToOpenOrCreate || filesToDiff) { return { filesToOpenOrCreate, filesToDiff }; } return undefined; } protected async restoreWorkbenchLayout(): Promise<void> { const restorePromises: Promise<void>[] = []; // Restore editors restorePromises.push((async () => { mark('willRestoreEditors'); // first ensure the editor part is restored await this.editorGroupService.whenRestored; // then see for editors to open as instructed let editors: IResourceEditorInputType[]; if (Array.isArray(this.state.editor.editorsToOpen)) { editors = this.state.editor.editorsToOpen; } else { editors = await this.state.editor.editorsToOpen; } if (editors.length) { await this.editorService.openEditors(editors); } mark('didRestoreEditors'); })()); // Restore default views const restoreDefaultViewsPromise = (async () => { if (this.state.views.defaults?.length) { mark('willOpenDefaultViews'); const defaultViews = [...this.state.views.defaults]; let locationsRestored: boolean[] = []; const tryOpenView = async (viewId: string, index: number) => { const location = this.viewDescriptorService.getViewLocationById(viewId); if (location) { // If the view is in the same location that has already been restored, remove it and continue if (locationsRestored[location]) { defaultViews.splice(index, 1); return; } const view = await this.viewsService.openView(viewId); if (view) { locationsRestored[location] = true; defaultViews.splice(index, 1); } } }; let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } // If we still have views left over, wait until all extensions have been registered and try again if (defaultViews.length) { await this.extensionService.whenInstalledExtensionsRegistered(); let i = -1; for (const viewId of defaultViews) { await tryOpenView(viewId, ++i); } } // If we opened a view in the sidebar, stop any restore there if (locationsRestored[ViewContainerLocation.Sidebar]) { this.state.sideBar.viewletToRestore = undefined; } // If we opened a view in the panel, stop any restore there if (locationsRestored[ViewContainerLocation.Panel]) { this.state.panel.panelToRestore = undefined; } mark('didOpenDefaultViews'); } })(); restorePromises.push(restoreDefaultViewsPromise); // Restore Sidebar restorePromises.push((async () => { // Restoring views could mean that sidebar already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.sideBar.viewletToRestore) { return; } mark('willRestoreViewlet'); const viewlet = await this.viewletService.openViewlet(this.state.sideBar.viewletToRestore); if (!viewlet) { await this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id); // fallback to default viewlet as needed } mark('didRestoreViewlet'); })()); // Restore Panel restorePromises.push((async () => { // Restoring views could mean that panel already // restored, as such we need to test again await restoreDefaultViewsPromise; if (!this.state.panel.panelToRestore) { return; } mark('willRestorePanel'); const panel = await this.panelService.openPanel(this.state.panel.panelToRestore!); if (!panel) { await this.panelService.openPanel(Registry.as<PanelRegistry>(PanelExtensions.Panels).getDefaultPanelId()); // fallback to default panel as needed } mark('didRestorePanel'); })()); // Restore Zen Mode if (this.state.zenMode.restore) { this.toggleZenMode(false, true); } // Restore Editor Center Mode if (this.state.editor.restoreCentered) { this.centerEditorLayout(true, true); } // Await restore to be done await Promise.all(restorePromises); } private updatePanelPosition() { const defaultPanelPosition = this.configurationService.getValue<string>(Settings.PANEL_POSITION); const panelPosition = this.storageService.get(Storage.PANEL_POSITION, StorageScope.WORKSPACE, defaultPanelPosition); this.state.panel.position = positionFromString(panelPosition || defaultPanelPosition); } registerPart(part: Part): void { this.parts.set(part.getId(), part); } protected getPart(key: Parts): Part { const part = this.parts.get(key); if (!part) { throw new Error(`Unknown part ${key}`); } return part; } isRestored(): boolean { return this.lifecycleService.phase >= LifecyclePhase.Restored; } hasFocus(part: Parts): boolean { const activeElement = document.activeElement; if (!activeElement) { return false; } const container = this.getContainer(part); return !!container && isAncestor(activeElement, container); } focusPart(part: Parts): void { switch (part) { case Parts.EDITOR_PART: this.editorGroupService.activeGroup.focus(); break; case Parts.PANEL_PART: const activePanel = this.panelService.getActivePanel(); if (activePanel) { activePanel.focus(); } break; case Parts.SIDEBAR_PART: const activeViewlet = this.viewletService.getActiveViewlet(); if (activeViewlet) { activeViewlet.focus(); } break; case Parts.ACTIVITYBAR_PART: this.activityBarService.focusActivityBar(); break; case Parts.STATUSBAR_PART: this.statusBarService.focus(); default: // Title Bar simply pass focus to container const container = this.getContainer(part); if (container) { container.focus(); } } } getContainer(part: Parts): HTMLElement | undefined { switch (part) { case Parts.TITLEBAR_PART: return this.getPart(Parts.TITLEBAR_PART).getContainer(); case Parts.ACTIVITYBAR_PART: return this.getPart(Parts.ACTIVITYBAR_PART).getContainer(); case Parts.SIDEBAR_PART: return this.getPart(Parts.SIDEBAR_PART).getContainer(); case Parts.PANEL_PART: return this.getPart(Parts.PANEL_PART).getContainer(); case Parts.EDITOR_PART: return this.getPart(Parts.EDITOR_PART).getContainer(); case Parts.STATUSBAR_PART: return this.getPart(Parts.STATUSBAR_PART).getContainer(); } } isVisible(part: Parts): boolean { switch (part) { case Parts.TITLEBAR_PART: if (getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { return false; } else if (!this.state.fullscreen && !isWeb) { return true; } else if (isMacintosh && isNative) { return false; } else if (this.state.menuBar.visibility === 'visible') { return true; } else if (this.state.menuBar.visibility === 'toggle' || this.state.menuBar.visibility === 'default') { return this.state.menuBar.toggled; } return false; case Parts.SIDEBAR_PART: return !this.state.sideBar.hidden; case Parts.PANEL_PART: return !this.state.panel.hidden; case Parts.STATUSBAR_PART: return !this.state.statusBar.hidden; case Parts.ACTIVITYBAR_PART: return !this.state.activityBar.hidden; case Parts.EDITOR_PART: return !this.state.editor.hidden; default: return true; // any other part cannot be hidden } } focus(): void { this.editorGroupService.activeGroup.focus(); } getDimension(part: Parts): Dimension | undefined { return this.getPart(part).dimension; } getMaximumEditorDimensions(): Dimension { const isColumn = this.state.panel.position === Position.RIGHT || this.state.panel.position === Position.LEFT; const takenWidth = (this.isVisible(Parts.ACTIVITYBAR_PART) ? this.activityBarPartView.minimumWidth : 0) + (this.isVisible(Parts.SIDEBAR_PART) ? this.sideBarPartView.minimumWidth : 0) + (this.isVisible(Parts.PANEL_PART) && isColumn ? this.panelPartView.minimumWidth : 0); const takenHeight = (this.isVisible(Parts.TITLEBAR_PART) ? this.titleBarPartView.minimumHeight : 0) + (this.isVisible(Parts.STATUSBAR_PART) ? this.statusBarPartView.minimumHeight : 0) + (this.isVisible(Parts.PANEL_PART) && !isColumn ? this.panelPartView.minimumHeight : 0); const availableWidth = this.dimension.width - takenWidth; const availableHeight = this.dimension.height - takenHeight; return { width: availableWidth, height: availableHeight }; } getWorkbenchContainer(): HTMLElement { return this.parent; } toggleZenMode(skipLayout?: boolean, restoring = false): void { this.state.zenMode.active = !this.state.zenMode.active; this.state.zenMode.transitionDisposables.clear(); const setLineNumbers = (lineNumbers?: LineNumbersType) => { const setEditorLineNumbers = (editor: IEditor) => { // To properly reset line numbers we need to read the configuration for each editor respecting it's uri. if (!lineNumbers && isCodeEditor(editor) && editor.hasModel()) { const model = editor.getModel(); lineNumbers = this.configurationService.getValue('editor.lineNumbers', { resource: model.uri, overrideIdentifier: model.getModeId() }); } if (!lineNumbers) { lineNumbers = this.configurationService.getValue('editor.lineNumbers'); } editor.updateOptions({ lineNumbers }); }; const editorControlSet = this.state.zenMode.editorWidgetSet; if (!lineNumbers) { // Reset line numbers on all editors visible and non-visible for (const editor of editorControlSet) { setEditorLineNumbers(editor); } editorControlSet.clear(); } else { this.editorService.visibleTextEditorControls.forEach(editorControl => { if (!editorControlSet.has(editorControl)) { editorControlSet.add(editorControl); this.state.zenMode.transitionDisposables.add(editorControl.onDidDispose(() => { editorControlSet.delete(editorControl); })); } setEditorLineNumbers(editorControl); }); } }; // Check if zen mode transitioned to full screen and if now we are out of zen mode // -> we need to go out of full screen (same goes for the centered editor layout) let toggleFullScreen = false; // Zen Mode Active if (this.state.zenMode.active) { const config: { fullScreen: boolean; centerLayout: boolean; hideTabs: boolean; hideActivityBar: boolean; hideStatusBar: boolean; hideLineNumbers: boolean; silentNotifications: boolean; } = this.configurationService.getValue('zenMode'); toggleFullScreen = !this.state.fullscreen && config.fullScreen; this.state.zenMode.transitionedToFullScreen = restoring ? config.fullScreen : toggleFullScreen; this.state.zenMode.transitionedToCenteredEditorLayout = !this.isEditorLayoutCentered() && config.centerLayout; this.state.zenMode.wasSideBarVisible = this.isVisible(Parts.SIDEBAR_PART); this.state.zenMode.wasPanelVisible = this.isVisible(Parts.PANEL_PART); this.setPanelHidden(true, true); this.setSideBarHidden(true, true); if (config.hideActivityBar) { this.setActivityBarHidden(true, true); } if (config.hideStatusBar) { this.setStatusBarHidden(true, true); } if (config.hideLineNumbers) { setLineNumbers('off'); this.state.zenMode.transitionDisposables.add(this.editorService.onDidVisibleEditorsChange(() => setLineNumbers('off'))); } if (config.hideTabs && this.editorGroupService.partOptions.showTabs) { this.state.zenMode.transitionDisposables.add(this.editorGroupService.enforcePartOptions({ showTabs: false })); } this.state.zenMode.setNotificationsFilter = config.silentNotifications; if (config.silentNotifications) { this.notificationService.setFilter(NotificationsFilter.ERROR); } this.state.zenMode.transitionDisposables.add(this.configurationService.onDidChangeConfiguration(c => { const silentNotificationsKey = 'zenMode.silentNotifications'; if (c.affectsConfiguration(silentNotificationsKey)) { const filter = this.configurationService.getValue(silentNotificationsKey) ? NotificationsFilter.ERROR : NotificationsFilter.OFF; this.notificationService.setFilter(filter); } })); if (config.centerLayout) { this.centerEditorLayout(true, true); } } // Zen Mode Inactive else { if (this.state.zenMode.wasPanelVisible) { this.setPanelHidden(false, true); } if (this.state.zenMode.wasSideBarVisible) { this.setSideBarHidden(false, true); } if (this.state.zenMode.transitionedToCenteredEditorLayout) { this.centerEditorLayout(false, true); } setLineNumbers(); // Status bar and activity bar visibility come from settings -> update their visibility. this.doUpdateLayoutConfiguration(true); this.focus(); if (this.state.zenMode.setNotificationsFilter) { this.notificationService.setFilter(NotificationsFilter.OFF); } toggleFullScreen = this.state.zenMode.transitionedToFullScreen && this.state.fullscreen; } if (!skipLayout) { this.layout(); } if (toggleFullScreen) { this.hostService.toggleFullScreen(); } // Event this._onZenModeChange.fire(this.state.zenMode.active); // State if (this.state.zenMode.active) { this.storageService.store(Storage.ZEN_MODE_ENABLED, true, StorageScope.WORKSPACE); // Exit zen mode on shutdown unless configured to keep this.state.zenMode.transitionDisposables.add(this.storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN && this.state.zenMode.active) { if (!this.configurationService.getValue(Settings.ZEN_MODE_RESTORE)) { this.toggleZenMode(true); // We will not restore zen mode, need to clear all zen mode state changes } } })); } else { this.storageService.remove(Storage.ZEN_MODE_ENABLED, StorageScope.WORKSPACE); } } private setStatusBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.statusBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.STATUSBAR_HIDDEN); } else { this.container.classList.remove(Classes.STATUSBAR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.statusBarPartView, !hidden); } protected createWorkbenchLayout(): void { const titleBar = this.getPart(Parts.TITLEBAR_PART); const editorPart = this.getPart(Parts.EDITOR_PART); const activityBar = this.getPart(Parts.ACTIVITYBAR_PART); const panelPart = this.getPart(Parts.PANEL_PART); const sideBar = this.getPart(Parts.SIDEBAR_PART); const statusBar = this.getPart(Parts.STATUSBAR_PART); // View references for all parts this.titleBarPartView = titleBar; this.sideBarPartView = sideBar; this.activityBarPartView = activityBar; this.editorPartView = editorPart; this.panelPartView = panelPart; this.statusBarPartView = statusBar; const viewMap = { [Parts.ACTIVITYBAR_PART]: this.activityBarPartView, [Parts.TITLEBAR_PART]: this.titleBarPartView, [Parts.EDITOR_PART]: this.editorPartView, [Parts.PANEL_PART]: this.panelPartView, [Parts.SIDEBAR_PART]: this.sideBarPartView, [Parts.STATUSBAR_PART]: this.statusBarPartView }; const fromJSON = ({ type }: { type: Parts }) => viewMap[type]; const workbenchGrid = SerializableGrid.deserialize( this.createGridDescriptor(), { fromJSON }, { proportionalLayout: false } ); this.container.prepend(workbenchGrid.element); this.container.setAttribute('role', 'application'); this.workbenchGrid = workbenchGrid; [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar].forEach((part: Part) => { this._register(part.onDidVisibilityChange((visible) => { if (part === sideBar) { this.setSideBarHidden(!visible, true); } else if (part === panelPart) { this.setPanelHidden(!visible, true); } else if (part === editorPart) { this.setEditorHidden(!visible, true); } this._onPartVisibilityChange.fire(); })); }); this._register(this.storageService.onWillSaveState(() => { const grid = this.workbenchGrid as SerializableGrid<ISerializableView>; const sideBarSize = this.state.sideBar.hidden ? grid.getViewCachedVisibleSize(this.sideBarPartView) : grid.getViewSize(this.sideBarPartView).width; this.storageService.store(Storage.SIDEBAR_SIZE, sideBarSize, StorageScope.GLOBAL); const panelSize = this.state.panel.hidden ? grid.getViewCachedVisibleSize(this.panelPartView) : (this.state.panel.position === Position.BOTTOM ? grid.getViewSize(this.panelPartView).height : grid.getViewSize(this.panelPartView).width); this.storageService.store(Storage.PANEL_SIZE, panelSize, StorageScope.GLOBAL); this.storageService.store(Storage.PANEL_DIMENSION, positionToString(this.state.panel.position), StorageScope.GLOBAL); const gridSize = grid.getViewSize(); this.storageService.store(Storage.GRID_WIDTH, gridSize.width, StorageScope.GLOBAL); this.storageService.store(Storage.GRID_HEIGHT, gridSize.height, StorageScope.GLOBAL); })); } getClientArea(): Dimension { return getClientArea(this.parent); } layout(): void { if (!this.disposed) { this._dimension = this.getClientArea(); position(this.container, 0, 0, 0, 0, 'relative'); size(this.container, this._dimension.width, this._dimension.height); // Layout the grid widget this.workbenchGrid.layout(this._dimension.width, this._dimension.height); // Emit as event this._onLayout.fire(this._dimension); } } isEditorLayoutCentered(): boolean { return this.state.editor.centered; } centerEditorLayout(active: boolean, skipLayout?: boolean): void { this.state.editor.centered = active; this.storageService.store(Storage.CENTERED_LAYOUT_ENABLED, active, StorageScope.WORKSPACE); let smartActive = active; const activeEditor = this.editorService.activeEditor; const isSideBySideLayout = activeEditor && activeEditor instanceof SideBySideEditorInput // DiffEditorInput inherits from SideBySideEditorInput but can still be functionally an inline editor. && (!(activeEditor instanceof DiffEditorInput) || this.configurationService.getValue('diffEditor.renderSideBySide')); const isCenteredLayoutAutoResizing = this.configurationService.getValue('workbench.editor.centeredLayoutAutoResize'); if ( isCenteredLayoutAutoResizing && (this.editorGroupService.groups.length > 1 || isSideBySideLayout) ) { smartActive = false; } // Enter Centered Editor Layout if (this.editorGroupService.isLayoutCentered() !== smartActive) { this.editorGroupService.centerLayout(smartActive); if (!skipLayout) { this.layout(); } } this._onCenteredLayoutChange.fire(this.state.editor.centered); } resizePart(part: Parts, sizeChange: number): void { const sizeChangePxWidth = this.workbenchGrid.width * sizeChange / 100; const sizeChangePxHeight = this.workbenchGrid.height * sizeChange / 100; let viewSize: IViewSize; switch (part) { case Parts.SIDEBAR_PART: viewSize = this.workbenchGrid.getViewSize(this.sideBarPartView); this.workbenchGrid.resizeView(this.sideBarPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); break; case Parts.PANEL_PART: viewSize = this.workbenchGrid.getViewSize(this.panelPartView); this.workbenchGrid.resizeView(this.panelPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); break; case Parts.EDITOR_PART: viewSize = this.workbenchGrid.getViewSize(this.editorPartView); // Single Editor Group if (this.editorGroupService.count === 1) { if (this.isVisible(Parts.SIDEBAR_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + sizeChangePxWidth, height: viewSize.height }); } else if (this.isVisible(Parts.PANEL_PART)) { this.workbenchGrid.resizeView(this.editorPartView, { width: viewSize.width + (this.getPanelPosition() !== Position.BOTTOM ? sizeChangePxWidth : 0), height: viewSize.height + (this.getPanelPosition() !== Position.BOTTOM ? 0 : sizeChangePxHeight) }); } } else { const activeGroup = this.editorGroupService.activeGroup; const { width, height } = this.editorGroupService.getSize(activeGroup); this.editorGroupService.setSize(activeGroup, { width: width + sizeChangePxWidth, height: height + sizeChangePxHeight }); } break; default: return; // Cannot resize other parts } } setActivityBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.activityBar.hidden = hidden; // Propagate to grid this.workbenchGrid.setViewVisible(this.activityBarPartView, !hidden); } setEditorHidden(hidden: boolean, skipLayout?: boolean): void { this.state.editor.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.EDITOR_HIDDEN); } else { this.container.classList.remove(Classes.EDITOR_HIDDEN); } // Propagate to grid this.workbenchGrid.setViewVisible(this.editorPartView, !hidden); // Remember in settings if (hidden) { this.storageService.store(Storage.EDITOR_HIDDEN, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.EDITOR_HIDDEN, StorageScope.WORKSPACE); } // The editor and panel cannot be hidden at the same time if (hidden && this.state.panel.hidden) { this.setPanelHidden(false, true); } } getLayoutClasses(): string[] { return coalesce([ this.state.sideBar.hidden ? Classes.SIDEBAR_HIDDEN : undefined, this.state.editor.hidden ? Classes.EDITOR_HIDDEN : undefined, this.state.panel.hidden ? Classes.PANEL_HIDDEN : undefined, this.state.statusBar.hidden ? Classes.STATUSBAR_HIDDEN : undefined, this.state.fullscreen ? Classes.FULLSCREEN : undefined ]); } setSideBarHidden(hidden: boolean, skipLayout?: boolean): void { this.state.sideBar.hidden = hidden; // Adjust CSS if (hidden) { this.container.classList.add(Classes.SIDEBAR_HIDDEN); } else { this.container.classList.remove(Classes.SIDEBAR_HIDDEN); } // If sidebar becomes hidden, also hide the current active Viewlet if any if (hidden && this.viewletService.getActiveViewlet()) { this.viewletService.hideActiveViewlet(); // Pass Focus to Editor or Panel if Sidebar is now hidden const activePanel = this.panelService.getActivePanel(); if (this.hasFocus(Parts.PANEL_PART) && activePanel) { activePanel.focus(); } else { this.focus(); } } // If sidebar becomes visible, show last active Viewlet or default viewlet else if (!hidden && !this.viewletService.getActiveViewlet()) { const viewletToOpen = this.viewletService.getLastActiveViewletId(); if (viewletToOpen) { const viewlet = this.viewletService.openViewlet(viewletToOpen, true); if (!viewlet) { this.viewletService.openViewlet(this.viewDescriptorService.getDefaultViewContainer(ViewContainerLocation.Sidebar)?.id, true); } } } // Propagate to grid this.workbenchGrid.setViewVisible(this.sideBarPartView, !hidden); // Remember in settings const defaultHidden = this.contextService.getWorkbenchState() === WorkbenchState.EMPTY; if (hidden !== defaultHidden) { this.storageService.store(Storage.SIDEBAR_HIDDEN, hidden ? 'true' : 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.SIDEBAR_HIDDEN, StorageScope.WORKSPACE); } } setPanelHidden(hidden: boolean, skipLayout?: boolean): void { const wasHidden = this.state.panel.hidden; this.state.panel.hidden = hidden; // Return if not initialized fully #105480 if (!this.workbenchGrid) { return; } const isPanelMaximized = this.isPanelMaximized(); const panelOpensMaximized = this.panelOpensMaximized(); // Adjust CSS if (hidden) { this.container.classList.add(Classes.PANEL_HIDDEN); } else { this.container.classList.remove(Classes.PANEL_HIDDEN); } // If panel part becomes hidden, also hide the current active panel if any let focusEditor = false; if (hidden && this.panelService.getActivePanel()) { this.panelService.hideActivePanel(); focusEditor = true; } // If panel part becomes visible, show last active panel or default panel else if (!hidden && !this.panelService.getActivePanel()) { const panelToOpen = this.panelService.getLastActivePanelId(); if (panelToOpen) { const focus = !skipLayout; this.panelService.openPanel(panelToOpen, focus); } } // If maximized and in process of hiding, unmaximize before hiding to allow caching of non-maximized size if (hidden && isPanelMaximized) { this.toggleMaximizedPanel(); } // Don't proceed if we have already done this before if (wasHidden === hidden) { return; } // Propagate layout changes to grid this.workbenchGrid.setViewVisible(this.panelPartView, !hidden); // If in process of showing, toggle whether or not panel is maximized if (!hidden) { if (isPanelMaximized !== panelOpensMaximized) { this.toggleMaximizedPanel(); } } else { // If in process of hiding, remember whether the panel is maximized or not this.state.panel.wasLastMaximized = isPanelMaximized; } // Remember in settings if (!hidden) { this.storageService.store(Storage.PANEL_HIDDEN, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_HIDDEN, StorageScope.WORKSPACE); // Remember this setting only when panel is hiding if (this.state.panel.wasLastMaximized) { this.storageService.store(Storage.PANEL_LAST_IS_MAXIMIZED, true, StorageScope.WORKSPACE); } else { this.storageService.remove(Storage.PANEL_LAST_IS_MAXIMIZED, StorageScope.WORKSPACE); } } if (focusEditor) { this.editorGroupService.activeGroup.focus(); // Pass focus to editor group if panel part is now hidden } } toggleMaximizedPanel(): void { const size = this.workbenchGrid.getViewSize(this.panelPartView); if (!this.isPanelMaximized()) { if (!this.state.panel.hidden) { if (this.state.panel.position === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_HEIGHT, this.state.panel.lastNonMaximizedHeight, StorageScope.GLOBAL); } else { this.state.panel.lastNonMaximizedWidth = size.width; this.storageService.store(Storage.PANEL_LAST_NON_MAXIMIZED_WIDTH, this.state.panel.lastNonMaximizedWidth, StorageScope.GLOBAL); } } this.setEditorHidden(true); } else { this.setEditorHidden(false); this.workbenchGrid.resizeView(this.panelPartView, { width: this.state.panel.position === Position.BOTTOM ? size.width : this.state.panel.lastNonMaximizedWidth, height: this.state.panel.position === Position.BOTTOM ? this.state.panel.lastNonMaximizedHeight : size.height }); } } /** * Returns whether or not the panel opens maximized */ private panelOpensMaximized() { const panelOpensMaximized = panelOpensMaximizedFromString(this.configurationService.getValue<string>(Settings.PANEL_OPENS_MAXIMIZED)); const panelLastIsMaximized = this.state.panel.wasLastMaximized; return panelOpensMaximized === PanelOpensMaximizedOptions.ALWAYS || (panelOpensMaximized === PanelOpensMaximizedOptions.REMEMBER_LAST && panelLastIsMaximized); } hasWindowBorder(): boolean { return this.state.windowBorder; } getWindowBorderWidth(): number { return this.state.windowBorder ? 2 : 0; } getWindowBorderRadius(): string | undefined { return this.state.windowBorder && isMacintosh ? '5px' : undefined; } isPanelMaximized(): boolean { if (!this.workbenchGrid) { return false; } return this.state.editor.hidden; } getSideBarPosition(): Position { return this.state.sideBar.position; } setMenubarVisibility(visibility: MenuBarVisibility, skipLayout: boolean): void { if (this.state.menuBar.visibility !== visibility) { this.state.menuBar.visibility = visibility; // Layout if (!skipLayout && this.workbenchGrid) { this.workbenchGrid.setViewVisible(this.titleBarPartView, this.isVisible(Parts.TITLEBAR_PART)); } } } getMenubarVisibility(): MenuBarVisibility { return this.state.menuBar.visibility; } getPanelPosition(): Position { return this.state.panel.position; } setPanelPosition(position: Position): void { if (this.state.panel.hidden) { this.setPanelHidden(false); } const panelPart = this.getPart(Parts.PANEL_PART); const oldPositionValue = positionToString(this.state.panel.position); const newPositionValue = positionToString(position); this.state.panel.position = position; // Save panel position this.storageService.store(Storage.PANEL_POSITION, newPositionValue, StorageScope.WORKSPACE); // Adjust CSS const panelContainer = assertIsDefined(panelPart.getContainer()); panelContainer.classList.remove(oldPositionValue); panelContainer.classList.add(newPositionValue); // Update Styles panelPart.updateStyles(); // Layout const size = this.workbenchGrid.getViewSize(this.panelPartView); const sideBarSize = this.workbenchGrid.getViewSize(this.sideBarPartView); // Save last non-maximized size for panel before move if (newPositionValue !== oldPositionValue && !this.state.editor.hidden) { // Save the current size of the panel for the new orthogonal direction // If moving down, save the width of the panel // Otherwise, save the height of the panel if (position === Position.BOTTOM) { this.state.panel.lastNonMaximizedWidth = size.width; } else if (positionFromString(oldPositionValue) === Position.BOTTOM) { this.state.panel.lastNonMaximizedHeight = size.height; } } if (position === Position.BOTTOM) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.height : this.state.panel.lastNonMaximizedHeight, this.editorPartView, Direction.Down); } else if (position === Position.RIGHT) { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Right); } else { this.workbenchGrid.moveView(this.panelPartView, this.state.editor.hidden ? size.width : this.state.panel.lastNonMaximizedWidth, this.editorPartView, Direction.Left); } // Reset sidebar to original size before shifting the panel this.workbenchGrid.resizeView(this.sideBarPartView, sideBarSize); this._onPanelPositionChange.fire(newPositionValue); } isWindowMaximized() { return this.state.maximized; } updateWindowMaximizedState(maximized: boolean) { if (this.state.maximized === maximized) { return; } this.state.maximized = maximized; this.updateWindowBorder(); this._onMaximizeChange.fire(maximized); } getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined { if (!this.workbenchGrid) { return undefined; } if (!this.isVisible(part)) { return undefined; } const neighborViews = this.workbenchGrid.getNeighborViews(this.getPart(part), direction, false); if (!neighborViews) { return undefined; } for (const neighborView of neighborViews) { const neighborPart = [Parts.ACTIVITYBAR_PART, Parts.EDITOR_PART, Parts.PANEL_PART, Parts.SIDEBAR_PART, Parts.STATUSBAR_PART, Parts.TITLEBAR_PART] .find(partId => this.getPart(partId) === neighborView && this.isVisible(partId)); if (neighborPart !== undefined) { return neighborPart; } } return undefined; } private arrangeEditorNodes(editorNode: ISerializedNode, panelNode: ISerializedNode, editorSectionWidth: number): ISerializedNode[] { switch (this.state.panel.position) { case Position.BOTTOM: return [{ type: 'branch', data: [editorNode, panelNode], size: editorSectionWidth }]; case Position.RIGHT: return [editorNode, panelNode]; case Position.LEFT: return [panelNode, editorNode]; } } private createGridDescriptor(): ISerializedGrid { const workbenchDimensions = this.getClientArea(); const width = this.storageService.getNumber(Storage.GRID_WIDTH, StorageScope.GLOBAL, workbenchDimensions.width); const height = this.storageService.getNumber(Storage.GRID_HEIGHT, StorageScope.GLOBAL, workbenchDimensions.height); const sideBarSize = this.storageService.getNumber(Storage.SIDEBAR_SIZE, StorageScope.GLOBAL, Math.min(workbenchDimensions.width / 4, 300)); const panelDimension = positionFromString(this.storageService.get(Storage.PANEL_DIMENSION, StorageScope.GLOBAL, 'bottom')); const fallbackPanelSize = this.state.panel.position === Position.BOTTOM ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4; const panelSize = panelDimension === this.state.panel.position ? this.storageService.getNumber(Storage.PANEL_SIZE, StorageScope.GLOBAL, fallbackPanelSize) : fallbackPanelSize; const titleBarHeight = this.titleBarPartView.minimumHeight; const statusBarHeight = this.statusBarPartView.minimumHeight; const activityBarWidth = this.activityBarPartView.minimumWidth; const middleSectionHeight = height - titleBarHeight - statusBarHeight; const editorSectionWidth = width - (this.state.activityBar.hidden ? 0 : activityBarWidth) - (this.state.sideBar.hidden ? 0 : sideBarSize); const activityBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.ACTIVITYBAR_PART }, size: activityBarWidth, visible: !this.state.activityBar.hidden }; const sideBarNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.SIDEBAR_PART }, size: sideBarSize, visible: !this.state.sideBar.hidden }; const editorNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.EDITOR_PART }, size: this.state.panel.position === Position.BOTTOM ? middleSectionHeight - (this.state.panel.hidden ? 0 : panelSize) : editorSectionWidth - (this.state.panel.hidden ? 0 : panelSize), visible: !this.state.editor.hidden }; const panelNode: ISerializedLeafNode = { type: 'leaf', data: { type: Parts.PANEL_PART }, size: panelSize, visible: !this.state.panel.hidden }; const editorSectionNode = this.arrangeEditorNodes(editorNode, panelNode, editorSectionWidth); const middleSection: ISerializedNode[] = this.state.sideBar.position === Position.LEFT ? [activityBarNode, sideBarNode, ...editorSectionNode] : [...editorSectionNode, sideBarNode, activityBarNode]; const result: ISerializedGrid = { root: { type: 'branch', size: width, data: [ { type: 'leaf', data: { type: Parts.TITLEBAR_PART }, size: titleBarHeight, visible: this.isVisible(Parts.TITLEBAR_PART) }, { type: 'branch', data: middleSection, size: middleSectionHeight }, { type: 'leaf', data: { type: Parts.STATUSBAR_PART }, size: statusBarHeight, visible: !this.state.statusBar.hidden } ] }, orientation: Orientation.VERTICAL, width, height }; return result; } dispose(): void { super.dispose(); this.disposed = true; } }
src/vs/workbench/browser/layout.ts
1
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0012786057777702808, 0.0001967501302715391, 0.00015785114374011755, 0.00017141243733931333, 0.00013236160157248378 ]
{ "id": 6, "code_window": [ "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n", "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => workbench.layout()));\n", "\n", "\t\t// Prevent the back/forward gestures in macOS\n", "\t\tthis._register(addDisposableListener(this.domElement, EventType.WHEEL, e => e.preventDefault(), { passive: false }));\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => {\n", "\t\t\tlogService.trace(`web.main#${isIOS && window.visualViewport ? 'visualViewport' : 'window'}Resize`);\n", "\t\t\tworkbench.layout();\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * 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 { getPathFromAmdModule } from 'vs/base/common/amd'; import * as path from 'vs/base/common/path'; import { URI } from 'vs/base/common/uri'; import { IFileQuery, IFolderQuery, ISerializedSearchProgressItem, isProgressMessage, QueryType } from 'vs/workbench/services/search/common/search'; import { SearchService } from 'vs/workbench/services/search/node/rawSearchService'; const TEST_FIXTURES = path.normalize(getPathFromAmdModule(require, './fixtures')); const TEST_FIXTURES2 = path.normalize(getPathFromAmdModule(require, './fixtures2')); const EXAMPLES_FIXTURES = path.join(TEST_FIXTURES, 'examples'); const MORE_FIXTURES = path.join(TEST_FIXTURES, 'more'); const TEST_ROOT_FOLDER: IFolderQuery = { folder: URI.file(TEST_FIXTURES) }; const ROOT_FOLDER_QUERY: IFolderQuery[] = [ TEST_ROOT_FOLDER ]; const MULTIROOT_QUERIES: IFolderQuery[] = [ { folder: URI.file(EXAMPLES_FIXTURES), folderName: 'examples_folder' }, { folder: URI.file(MORE_FIXTURES) } ]; async function doSearchTest(query: IFileQuery, expectedResultCount: number | Function): Promise<void> { const svc = new SearchService(); const results: ISerializedSearchProgressItem[] = []; await svc.doFileSearch(query, e => { if (!isProgressMessage(e)) { if (Array.isArray(e)) { results.push(...e); } else { results.push(e); } } }); assert.equal(results.length, expectedResultCount, `rg ${results.length} !== ${expectedResultCount}`); } suite('FileSearch-integration', function () { this.timeout(1000 * 60); // increase timeout for this suite test('File - simple', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY }; return doSearchTest(config, 14); }); test('File - filepattern', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'anotherfile' }; return doSearchTest(config, 1); }); test('File - exclude', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'file', excludePattern: { '**/anotherfolder/**': true } }; return doSearchTest(config, 2); }); test('File - multiroot', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: MULTIROOT_QUERIES, filePattern: 'file', excludePattern: { '**/anotherfolder/**': true } }; return doSearchTest(config, 2); }); test('File - multiroot with folder name', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: MULTIROOT_QUERIES, filePattern: 'examples_folder anotherfile' }; return doSearchTest(config, 1); }); test('File - multiroot with folder name and sibling exclude', () => { const config: IFileQuery = { type: QueryType.File, folderQueries: [ { folder: URI.file(TEST_FIXTURES), folderName: 'folder1' }, { folder: URI.file(TEST_FIXTURES2) } ], filePattern: 'folder1 site', excludePattern: { '*.css': { when: '$(basename).less' } } }; return doSearchTest(config, 1); }); });
src/vs/workbench/services/search/test/node/fileSearch.integrationTest.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0001765547931427136, 0.0001731218071654439, 0.0001657006359891966, 0.00017490494064986706, 0.0000038046289319026982 ]
{ "id": 6, "code_window": [ "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n", "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => workbench.layout()));\n", "\n", "\t\t// Prevent the back/forward gestures in macOS\n", "\t\tthis._register(addDisposableListener(this.domElement, EventType.WHEEL, e => e.preventDefault(), { passive: false }));\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => {\n", "\t\t\tlogService.trace(`web.main#${isIOS && window.visualViewport ? 'visualViewport' : 'window'}Resize`);\n", "\t\t\tworkbench.layout();\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { EditorDescriptor, Extensions as EditorExtensions, IEditorRegistry } from 'vs/workbench/browser/editor'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { Extensions as EditorInputExtensions, IEditorInputFactoryRegistry } from 'vs/workbench/common/editor'; import { CustomEditorInputFactory } from 'vs/workbench/contrib/customEditor/browser/customEditorInputFactory'; import { ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor'; import { WebviewEditor } from 'vs/workbench/contrib/webviewPanel/browser/webviewEditor'; import { CustomEditorInput } from './customEditorInput'; import { CustomEditorContribution, CustomEditorService } from './customEditors'; registerSingleton(ICustomEditorService, CustomEditorService); Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench) .registerWorkbenchContribution(CustomEditorContribution, LifecyclePhase.Starting); Registry.as<IEditorRegistry>(EditorExtensions.Editors) .registerEditor( EditorDescriptor.create( WebviewEditor, WebviewEditor.ID, 'Webview Editor', ), [ new SyncDescriptor(CustomEditorInput) ]); Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories) .registerEditorInputFactory( CustomEditorInputFactory.ID, CustomEditorInputFactory); Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories) .registerCustomEditorInputFactory(Schemas.vscodeCustomEditor, CustomEditorInputFactory);
src/vs/workbench/contrib/customEditor/browser/customEditor.contribution.ts
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.0001762597676133737, 0.00017341261263936758, 0.00016941220383159816, 0.00017518243112135679, 0.0000028477222713263473 ]
{ "id": 6, "code_window": [ "\n", "\t\t// Layout\n", "\t\tconst viewport = isIOS && window.visualViewport ? window.visualViewport /** Visual viewport */ : window /** Layout viewport */;\n", "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => workbench.layout()));\n", "\n", "\t\t// Prevent the back/forward gestures in macOS\n", "\t\tthis._register(addDisposableListener(this.domElement, EventType.WHEEL, e => e.preventDefault(), { passive: false }));\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(addDisposableListener(viewport, EventType.RESIZE, () => {\n", "\t\t\tlogService.trace(`web.main#${isIOS && window.visualViewport ? 'visualViewport' : 'window'}Resize`);\n", "\t\t\tworkbench.layout();\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/browser/web.main.ts", "type": "replace", "edit_start_line_idx": 112 }
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><style>.st0{fill:#f6f6f6;fill-opacity:0}.st1{fill:#fff}.st2{fill:#167abf}</style><path class="st0" d="M1024 1024H0V0h1024v1024z"/><path class="st1" d="M1024 85.333v853.333H0V85.333h1024z"/><path class="st2" d="M0 85.333h298.667v853.333H0V85.333zm1024 0v853.333H384V85.333h640zm-554.667 160h341.333v-64H469.333v64zm341.334 533.334H469.333v64h341.333l.001-64zm128-149.334H597.333v64h341.333l.001-64zm0-149.333H597.333v64h341.333l.001-64zm0-149.333H597.333v64h341.333l.001-64z"/></svg>
src/vs/workbench/browser/media/code-icon.svg
0
https://github.com/microsoft/vscode/commit/eb9f371678b170203ef6761ffc224856804de4ef
[ 0.00017193543317262083, 0.00017193543317262083, 0.00017193543317262083, 0.00017193543317262083, 0 ]
{ "id": 0, "code_window": [ "\n", "export function MixedTypeAnnotation() {\n", " this.word(\"mixed\");\n", "}\n", "\n", "export function NullableTypeAnnotation(node: Object) {\n", " this.token(\"?\");\n", " this.print(node.typeAnnotation, node);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export function EmptyTypeAnnotation() {\n", " this.word(\"empty\");\n", "}\n", "\n" ], "file_path": "packages/babel-generator/src/generators/flow.js", "type": "add", "edit_start_line_idx": 169 }
/* eslint max-len: 0 */ export function AnyTypeAnnotation() { this.word("any"); } export function ArrayTypeAnnotation(node: Object) { this.print(node.elementType, node); this.token("["); this.token("]"); } export function BooleanTypeAnnotation() { this.word("boolean"); } export function BooleanLiteralTypeAnnotation(node: Object) { this.word(node.value ? "true" : "false"); } export function NullLiteralTypeAnnotation() { this.word("null"); } export function DeclareClass(node: Object) { this.word("declare"); this.space(); this.word("class"); this.space(); this._interfaceish(node); } export function DeclareFunction(node: Object) { this.word("declare"); this.space(); this.word("function"); this.space(); this.print(node.id, node); this.print(node.id.typeAnnotation.typeAnnotation, node); this.semicolon(); } export function DeclareInterface(node: Object) { this.word("declare"); this.space(); this.InterfaceDeclaration(node); } export function DeclareModule(node: Object) { this.word("declare"); this.space(); this.word("module"); this.space(); this.print(node.id, node); this.space(); this.print(node.body, node); } export function DeclareModuleExports(node: Object) { this.word("declare"); this.space(); this.word("module"); this.token("."); this.word("exports"); this.print(node.typeAnnotation, node); } export function DeclareTypeAlias(node: Object) { this.word("declare"); this.space(); this.TypeAlias(node); } export function DeclareVariable(node: Object) { this.word("declare"); this.space(); this.word("var"); this.space(); this.print(node.id, node); this.print(node.id.typeAnnotation, node); this.semicolon(); } export function ExistentialTypeParam() { this.token("*"); } export function FunctionTypeAnnotation(node: Object, parent: Object) { this.print(node.typeParameters, node); this.token("("); this.printList(node.params, node); if (node.rest) { if (node.params.length) { this.token(","); this.space(); } this.token("..."); this.print(node.rest, node); } this.token(")"); // this node type is overloaded, not sure why but it makes it EXTREMELY annoying if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { this.token(":"); } else { this.space(); this.token("=>"); } this.space(); this.print(node.returnType, node); } export function FunctionTypeParam(node: Object) { this.print(node.name, node); if (node.optional) this.token("?"); this.token(":"); this.space(); this.print(node.typeAnnotation, node); } export function InterfaceExtends(node: Object) { this.print(node.id, node); this.print(node.typeParameters, node); } export { InterfaceExtends as ClassImplements, InterfaceExtends as GenericTypeAnnotation }; export function _interfaceish(node: Object) { this.print(node.id, node); this.print(node.typeParameters, node); if (node.extends.length) { this.space(); this.word("extends"); this.space(); this.printList(node.extends, node); } if (node.mixins && node.mixins.length) { this.space(); this.word("mixins"); this.space(); this.printList(node.mixins, node); } this.space(); this.print(node.body, node); } export function InterfaceDeclaration(node: Object) { this.word("interface"); this.space(); this._interfaceish(node); } function andSeparator() { this.space(); this.token("&"); this.space(); } export function IntersectionTypeAnnotation(node: Object) { this.printJoin(node.types, node, { separator: andSeparator }); } export function MixedTypeAnnotation() { this.word("mixed"); } export function NullableTypeAnnotation(node: Object) { this.token("?"); this.print(node.typeAnnotation, node); } export { NumericLiteral as NumericLiteralTypeAnnotation, StringLiteral as StringLiteralTypeAnnotation, } from "./types"; export function NumberTypeAnnotation() { this.word("number"); } export function StringTypeAnnotation() { this.word("string"); } export function ThisTypeAnnotation() { this.word("this"); } export function TupleTypeAnnotation(node: Object) { this.token("["); this.printList(node.types, node); this.token("]"); } export function TypeofTypeAnnotation(node: Object) { this.word("typeof"); this.space(); this.print(node.argument, node); } export function TypeAlias(node: Object) { this.word("type"); this.space(); this.print(node.id, node); this.print(node.typeParameters, node); this.space(); this.token("="); this.space(); this.print(node.right, node); this.semicolon(); } export function TypeAnnotation(node: Object) { this.token(":"); this.space(); if (node.optional) this.token("?"); this.print(node.typeAnnotation, node); } export function TypeParameter(node: Object) { if (node.variance === "plus") { this.token("+"); } else if (node.variance === "minus") { this.token("-"); } this.word(node.name); if (node.bound) { this.print(node.bound, node); } if (node.default) { this.space(); this.token("="); this.space(); this.print(node.default, node); } } export function TypeParameterInstantiation(node: Object) { this.token("<"); this.printList(node.params, node, {}); this.token(">"); } export { TypeParameterInstantiation as TypeParameterDeclaration }; export function ObjectTypeAnnotation(node: Object) { if (node.exact) { this.token("{|"); } else { this.token("{"); } let props = node.properties.concat(node.callProperties, node.indexers); if (props.length) { this.space(); this.printJoin(props, node, { indent: true, statement: true, iterator: () => { if (props.length !== 1) { this.semicolon(); this.space(); } } }); this.space(); } if (node.exact) { this.token("|}"); } else { this.token("}"); } } export function ObjectTypeCallProperty(node: Object) { if (node.static) { this.word("static"); this.space(); } this.print(node.value, node); } export function ObjectTypeIndexer(node: Object) { if (node.static) { this.word("static"); this.space(); } this.token("["); this.print(node.id, node); this.token(":"); this.space(); this.print(node.key, node); this.token("]"); this.token(":"); this.space(); this.print(node.value, node); } export function ObjectTypeProperty(node: Object) { if (node.static) { this.word("static"); this.space(); } this.print(node.key, node); if (node.optional) this.token("?"); this.token(":"); this.space(); this.print(node.value, node); } export function QualifiedTypeIdentifier(node: Object) { this.print(node.qualification, node); this.token("."); this.print(node.id, node); } function orSeparator() { this.space(); this.token("|"); this.space(); } export function UnionTypeAnnotation(node: Object) { this.printJoin(node.types, node, { separator: orSeparator }); } export function TypeCastExpression(node: Object) { this.token("("); this.print(node.expression, node); this.print(node.typeAnnotation, node); this.token(")"); } export function VoidTypeAnnotation() { this.word("void"); }
packages/babel-generator/src/generators/flow.js
1
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.9889339208602905, 0.13914963603019714, 0.0001914417080115527, 0.010350113734602928, 0.28993600606918335 ]
{ "id": 0, "code_window": [ "\n", "export function MixedTypeAnnotation() {\n", " this.word(\"mixed\");\n", "}\n", "\n", "export function NullableTypeAnnotation(node: Object) {\n", " this.token(\"?\");\n", " this.print(node.typeAnnotation, node);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export function EmptyTypeAnnotation() {\n", " this.word(\"empty\");\n", "}\n", "\n" ], "file_path": "packages/babel-generator/src/generators/flow.js", "type": "add", "edit_start_line_idx": 169 }
var Foo = require("Foo"); var _ref = <Foo />; function render() { return _ref; }
packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/constructor/expected.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017096844385378063, 0.00017096844385378063, 0.00017096844385378063, 0.00017096844385378063, 0 ]
{ "id": 0, "code_window": [ "\n", "export function MixedTypeAnnotation() {\n", " this.word(\"mixed\");\n", "}\n", "\n", "export function NullableTypeAnnotation(node: Object) {\n", " this.token(\"?\");\n", " this.print(node.typeAnnotation, node);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export function EmptyTypeAnnotation() {\n", " this.word(\"empty\");\n", "}\n", "\n" ], "file_path": "packages/babel-generator/src/generators/flow.js", "type": "add", "edit_start_line_idx": 169 }
var a = { foo() { return 'A'; } }; var b = { __proto__: a, foo() { return super.foo() + ' B'; } }; var c = { __proto__: b, foo() { return super.foo() + ' C'; } }; var d = { __proto__: c, foo() { return super.foo() + ' D'; } }; // ---------------------------------------------------------------------------- assert.equal('A B C D', d.foo());
packages/babel-preset-es2015/test/fixtures/traceur/SuperObjectLiteral/SuperChaining.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017484198906458914, 0.00017250917153432965, 0.00017136814130935818, 0.00017191328515764326, 0.000001369178676213778 ]
{ "id": 0, "code_window": [ "\n", "export function MixedTypeAnnotation() {\n", " this.word(\"mixed\");\n", "}\n", "\n", "export function NullableTypeAnnotation(node: Object) {\n", " this.token(\"?\");\n", " this.print(node.typeAnnotation, node);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export function EmptyTypeAnnotation() {\n", " this.word(\"empty\");\n", "}\n", "\n" ], "file_path": "packages/babel-generator/src/generators/flow.js", "type": "add", "edit_start_line_idx": 169 }
import _v from "mod"; export { _v as v }; import * as _ns from "mod"; export { _ns as ns };
packages/babel-plugin-transform-export-extensions/test/fixtures/export-extensions/namespace-compound-es6/expected.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017422674864064902, 0.00017422674864064902, 0.00017422674864064902, 0.00017422674864064902, 0 ]
{ "id": 1, "code_window": [ " } else if (baseName === \"any\") {\n", " return t.isAnyTypeAnnotation(type);\n", " } else if (baseName === \"mixed\") {\n", " return t.isMixedTypeAnnotation(type);\n", " } else if (baseName === \"void\") {\n", " return t.isVoidTypeAnnotation(type);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " } else if (baseName === \"empty\") {\n", " return t.isEmptyTypeAnnotation(type);\n" ], "file_path": "packages/babel-traverse/src/path/inference/index.js", "type": "add", "edit_start_line_idx": 75 }
import type NodePath from "./index"; import * as inferers from "./inferers"; import * as t from "babel-types"; /** * Infer the type of the current `NodePath`. */ export function getTypeAnnotation(): Object { if (this.typeAnnotation) return this.typeAnnotation; let type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; } /** * todo: split up this method */ export function _getTypeAnnotation(): ?Object { let node = this.node; if (!node) { // handle initializerless variables, add in checks for loop initializers too if (this.key === "init" && this.parentPath.isVariableDeclarator()) { let declar = this.parentPath.parentPath; let declarParent = declar.parentPath; // for (let NODE in bar) {} if (declar.key === "left" && declarParent.isForInStatement()) { return t.stringTypeAnnotation(); } // for (let NODE of bar) {} if (declar.key === "left" && declarParent.isForOfStatement()) { return t.anyTypeAnnotation(); } return t.voidTypeAnnotation(); } else { return; } } if (node.typeAnnotation) { return node.typeAnnotation; } let inferer = inferers[node.type]; if (inferer) { return inferer.call(this, node); } inferer = inferers[this.parentPath.type]; if (inferer && inferer.validParent) { return this.parentPath.getTypeAnnotation(); } } export function isBaseType(baseName: string, soft?: boolean): boolean { return _isBaseType(baseName, this.getTypeAnnotation(), soft); } function _isBaseType(baseName: string, type?, soft?): boolean { if (baseName === "string") { return t.isStringTypeAnnotation(type); } else if (baseName === "number") { return t.isNumberTypeAnnotation(type); } else if (baseName === "boolean") { return t.isBooleanTypeAnnotation(type); } else if (baseName === "any") { return t.isAnyTypeAnnotation(type); } else if (baseName === "mixed") { return t.isMixedTypeAnnotation(type); } else if (baseName === "void") { return t.isVoidTypeAnnotation(type); } else { if (soft) { return false; } else { throw new Error(`Unknown base type ${baseName}`); } } } export function couldBeBaseType(name: string): boolean { let type = this.getTypeAnnotation(); if (t.isAnyTypeAnnotation(type)) return true; if (t.isUnionTypeAnnotation(type)) { for (let type2 of (type.types: Array<Object>)) { if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { return true; } } return false; } else { return _isBaseType(name, type, true); } } export function baseTypeStrictlyMatches(right: NodePath) { let left = this.getTypeAnnotation(); right = right.getTypeAnnotation(); if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { return right.type === left.type; } } export function isGenericType(genericName: string): boolean { let type = this.getTypeAnnotation(); return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); }
packages/babel-traverse/src/path/inference/index.js
1
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.997680127620697, 0.08491436392068863, 0.000214065657928586, 0.0023903818801045418, 0.27521219849586487 ]
{ "id": 1, "code_window": [ " } else if (baseName === \"any\") {\n", " return t.isAnyTypeAnnotation(type);\n", " } else if (baseName === \"mixed\") {\n", " return t.isMixedTypeAnnotation(type);\n", " } else if (baseName === \"void\") {\n", " return t.isVoidTypeAnnotation(type);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " } else if (baseName === \"empty\") {\n", " return t.isEmptyTypeAnnotation(type);\n" ], "file_path": "packages/babel-traverse/src/path/inference/index.js", "type": "add", "edit_start_line_idx": 75 }
var x = 0; function* f() { x++; } var g = f(); assert.equal(x, 0); assert.deepEqual(g.next(), {done: true, value: undefined}); assert.equal(x, 1);
packages/babel-preset-es2015/test/fixtures/traceur/Yield/GeneratorWithoutYieldOrReturn.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017693145491648465, 0.00017615596880204976, 0.00017538048268761486, 0.00017615596880204976, 7.754861144348979e-7 ]
{ "id": 1, "code_window": [ " } else if (baseName === \"any\") {\n", " return t.isAnyTypeAnnotation(type);\n", " } else if (baseName === \"mixed\") {\n", " return t.isMixedTypeAnnotation(type);\n", " } else if (baseName === \"void\") {\n", " return t.isVoidTypeAnnotation(type);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " } else if (baseName === \"empty\") {\n", " return t.isEmptyTypeAnnotation(type);\n" ], "file_path": "packages/babel-traverse/src/path/inference/index.js", "type": "add", "edit_start_line_idx": 75 }
define(["exports", "foo"], function (exports, _foo) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "foo", { enumerable: true, get: function () { return _foo.foo; } }); });
packages/babel-plugin-transform-es2015-modules-amd/test/fixtures/amd/export-from-2/expected.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017616567492950708, 0.00017390689754392952, 0.00017164812015835196, 0.00017390689754392952, 0.0000022587773855775595 ]
{ "id": 1, "code_window": [ " } else if (baseName === \"any\") {\n", " return t.isAnyTypeAnnotation(type);\n", " } else if (baseName === \"mixed\") {\n", " return t.isMixedTypeAnnotation(type);\n", " } else if (baseName === \"void\") {\n", " return t.isVoidTypeAnnotation(type);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " } else if (baseName === \"empty\") {\n", " return t.isEmptyTypeAnnotation(type);\n" ], "file_path": "packages/babel-traverse/src/path/inference/index.js", "type": "add", "edit_start_line_idx": 75 }
var x = { a: 5, get ["a"]() { return 6; } };
packages/babel-plugin-transform-es2015-duplicate-keys/test/fixtures/duplicate-keys/getter/expected.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017432362074032426, 0.00017432362074032426, 0.00017432362074032426, 0.00017432362074032426, 0 ]
{ "id": 2, "code_window": [ "\n", "See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n", "\n", "\n", "### t.newExpression(callee, arguments)\n", "\n", "See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### t.emptyTypeAnnotation()\n", "\n", "See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n" ], "file_path": "packages/babel-types/README.md", "type": "add", "edit_start_line_idx": 757 }
import type NodePath from "./index"; import * as inferers from "./inferers"; import * as t from "babel-types"; /** * Infer the type of the current `NodePath`. */ export function getTypeAnnotation(): Object { if (this.typeAnnotation) return this.typeAnnotation; let type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; } /** * todo: split up this method */ export function _getTypeAnnotation(): ?Object { let node = this.node; if (!node) { // handle initializerless variables, add in checks for loop initializers too if (this.key === "init" && this.parentPath.isVariableDeclarator()) { let declar = this.parentPath.parentPath; let declarParent = declar.parentPath; // for (let NODE in bar) {} if (declar.key === "left" && declarParent.isForInStatement()) { return t.stringTypeAnnotation(); } // for (let NODE of bar) {} if (declar.key === "left" && declarParent.isForOfStatement()) { return t.anyTypeAnnotation(); } return t.voidTypeAnnotation(); } else { return; } } if (node.typeAnnotation) { return node.typeAnnotation; } let inferer = inferers[node.type]; if (inferer) { return inferer.call(this, node); } inferer = inferers[this.parentPath.type]; if (inferer && inferer.validParent) { return this.parentPath.getTypeAnnotation(); } } export function isBaseType(baseName: string, soft?: boolean): boolean { return _isBaseType(baseName, this.getTypeAnnotation(), soft); } function _isBaseType(baseName: string, type?, soft?): boolean { if (baseName === "string") { return t.isStringTypeAnnotation(type); } else if (baseName === "number") { return t.isNumberTypeAnnotation(type); } else if (baseName === "boolean") { return t.isBooleanTypeAnnotation(type); } else if (baseName === "any") { return t.isAnyTypeAnnotation(type); } else if (baseName === "mixed") { return t.isMixedTypeAnnotation(type); } else if (baseName === "void") { return t.isVoidTypeAnnotation(type); } else { if (soft) { return false; } else { throw new Error(`Unknown base type ${baseName}`); } } } export function couldBeBaseType(name: string): boolean { let type = this.getTypeAnnotation(); if (t.isAnyTypeAnnotation(type)) return true; if (t.isUnionTypeAnnotation(type)) { for (let type2 of (type.types: Array<Object>)) { if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { return true; } } return false; } else { return _isBaseType(name, type, true); } } export function baseTypeStrictlyMatches(right: NodePath) { let left = this.getTypeAnnotation(); right = right.getTypeAnnotation(); if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { return right.type === left.type; } } export function isGenericType(genericName: string): boolean { let type = this.getTypeAnnotation(); return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); }
packages/babel-traverse/src/path/inference/index.js
1
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.021033545956015587, 0.002219819463789463, 0.0001722348970361054, 0.0002875531790778041, 0.005691108759492636 ]
{ "id": 2, "code_window": [ "\n", "See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n", "\n", "\n", "### t.newExpression(callee, arguments)\n", "\n", "See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### t.emptyTypeAnnotation()\n", "\n", "See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n" ], "file_path": "packages/babel-types/README.md", "type": "add", "edit_start_line_idx": 757 }
function* yieldUndefinedGenerator1() { yield 1; yield; yield 2; } function* yieldUndefinedGenerator2() { yield 1; yield undefined; yield 2; } function accumulate(iterator) { var result = ''; for (var value of iterator) { result = result + String(value); } return result; } // ---------------------------------------------------------------------------- assert.equal('1undefined2', accumulate(yieldUndefinedGenerator1())); assert.equal('1undefined2', accumulate(yieldUndefinedGenerator2()));
packages/babel-preset-es2015/test/fixtures/traceur/Yield/YieldUndefinedGenerator.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.0001778136211214587, 0.0001742699387250468, 0.0001698246196610853, 0.00017517157539259642, 0.000003323226110296673 ]
{ "id": 2, "code_window": [ "\n", "See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n", "\n", "\n", "### t.newExpression(callee, arguments)\n", "\n", "See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### t.emptyTypeAnnotation()\n", "\n", "See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n" ], "file_path": "packages/babel-types/README.md", "type": "add", "edit_start_line_idx": 757 }
var x = { a: 5, get a() {return 6;} };
packages/babel-plugin-transform-es2015-duplicate-keys/test/fixtures/duplicate-keys/getter/actual.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017539919645059854, 0.00017539919645059854, 0.00017539919645059854, 0.00017539919645059854, 0 ]
{ "id": 2, "code_window": [ "\n", "See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n", "\n", "\n", "### t.newExpression(callee, arguments)\n", "\n", "See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### t.emptyTypeAnnotation()\n", "\n", "See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`.\n", "\n", "Aliases: `Flow`, `FlowBaseAnnotation`\n" ], "file_path": "packages/babel-types/README.md", "type": "add", "edit_start_line_idx": 757 }
{ "throws": "\"MULTIPLIER\" is read-only" }
packages/babel-plugin-check-es2015-constants/test/fixtures/general/no-for-in/options.json
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.0001685725146671757, 0.0001685725146671757, 0.0001685725146671757, 0.0001685725146671757, 0 ]
{ "id": 3, "code_window": [ "\n", "defineType(\"MixedTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n", "defineType(\"NullableTypeAnnotation\", {\n", " visitor: [\"typeAnnotation\"],\n", " aliases: [\"Flow\"],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "defineType(\"EmptyTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n" ], "file_path": "packages/babel-types/src/definitions/flow.js", "type": "add", "edit_start_line_idx": 169 }
import type NodePath from "./index"; import * as inferers from "./inferers"; import * as t from "babel-types"; /** * Infer the type of the current `NodePath`. */ export function getTypeAnnotation(): Object { if (this.typeAnnotation) return this.typeAnnotation; let type = this._getTypeAnnotation() || t.anyTypeAnnotation(); if (t.isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; } /** * todo: split up this method */ export function _getTypeAnnotation(): ?Object { let node = this.node; if (!node) { // handle initializerless variables, add in checks for loop initializers too if (this.key === "init" && this.parentPath.isVariableDeclarator()) { let declar = this.parentPath.parentPath; let declarParent = declar.parentPath; // for (let NODE in bar) {} if (declar.key === "left" && declarParent.isForInStatement()) { return t.stringTypeAnnotation(); } // for (let NODE of bar) {} if (declar.key === "left" && declarParent.isForOfStatement()) { return t.anyTypeAnnotation(); } return t.voidTypeAnnotation(); } else { return; } } if (node.typeAnnotation) { return node.typeAnnotation; } let inferer = inferers[node.type]; if (inferer) { return inferer.call(this, node); } inferer = inferers[this.parentPath.type]; if (inferer && inferer.validParent) { return this.parentPath.getTypeAnnotation(); } } export function isBaseType(baseName: string, soft?: boolean): boolean { return _isBaseType(baseName, this.getTypeAnnotation(), soft); } function _isBaseType(baseName: string, type?, soft?): boolean { if (baseName === "string") { return t.isStringTypeAnnotation(type); } else if (baseName === "number") { return t.isNumberTypeAnnotation(type); } else if (baseName === "boolean") { return t.isBooleanTypeAnnotation(type); } else if (baseName === "any") { return t.isAnyTypeAnnotation(type); } else if (baseName === "mixed") { return t.isMixedTypeAnnotation(type); } else if (baseName === "void") { return t.isVoidTypeAnnotation(type); } else { if (soft) { return false; } else { throw new Error(`Unknown base type ${baseName}`); } } } export function couldBeBaseType(name: string): boolean { let type = this.getTypeAnnotation(); if (t.isAnyTypeAnnotation(type)) return true; if (t.isUnionTypeAnnotation(type)) { for (let type2 of (type.types: Array<Object>)) { if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { return true; } } return false; } else { return _isBaseType(name, type, true); } } export function baseTypeStrictlyMatches(right: NodePath) { let left = this.getTypeAnnotation(); right = right.getTypeAnnotation(); if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { return right.type === left.type; } } export function isGenericType(genericName: string): boolean { let type = this.getTypeAnnotation(); return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); }
packages/babel-traverse/src/path/inference/index.js
1
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.010925259441137314, 0.0016462899511680007, 0.00024514709366485476, 0.0007431311532855034, 0.002829519798979163 ]
{ "id": 3, "code_window": [ "\n", "defineType(\"MixedTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n", "defineType(\"NullableTypeAnnotation\", {\n", " visitor: [\"typeAnnotation\"],\n", " aliases: [\"Flow\"],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "defineType(\"EmptyTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n" ], "file_path": "packages/babel-types/src/definitions/flow.js", "type": "add", "edit_start_line_idx": 169 }
var x = {}; x.key = "value";
packages/babel-plugin-check-es2015-constants/test/fixtures/general/ignore-member-expressions/expected.js
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.0001765494089340791, 0.0001765494089340791, 0.0001765494089340791, 0.0001765494089340791, 0 ]
{ "id": 3, "code_window": [ "\n", "defineType(\"MixedTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n", "defineType(\"NullableTypeAnnotation\", {\n", " visitor: [\"typeAnnotation\"],\n", " aliases: [\"Flow\"],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "defineType(\"EmptyTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n" ], "file_path": "packages/babel-types/src/definitions/flow.js", "type": "add", "edit_start_line_idx": 169 }
{ "throws": "The @jsx React.DOM pragma has been deprecated as of React 0.12" }
packages/babel-plugin-transform-react-jsx/test/fixtures/react/throw-if-custom-jsx-comment-sets-react-dom-simple/options.json
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.0001713621022645384, 0.0001713621022645384, 0.0001713621022645384, 0.0001713621022645384, 0 ]
{ "id": 3, "code_window": [ "\n", "defineType(\"MixedTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n", "defineType(\"NullableTypeAnnotation\", {\n", " visitor: [\"typeAnnotation\"],\n", " aliases: [\"Flow\"],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "defineType(\"EmptyTypeAnnotation\", {\n", " aliases: [\"Flow\", \"FlowBaseAnnotation\"]\n", "});\n", "\n" ], "file_path": "packages/babel-types/src/definitions/flow.js", "type": "add", "edit_start_line_idx": 169 }
# babel-helper-builder-react-jsx ## Usage ```javascript type ElementState = { tagExpr: Object; // tag node tagName: string; // raw string tag name args: Array<Object>; // array of call arguments call?: Object; // optional call property that can be set to override the call expression returned pre?: Function; // function called with (state: ElementState) before building attribs post?: Function; // function called with (state: ElementState) after building attribs }; require("babel-helper-builder-react-jsx")({ pre: function (state: ElementState) { // called before building the element }, post: function (state: ElementState) { // called after building the element } }); ```
packages/babel-helper-builder-react-jsx/README.md
0
https://github.com/babel/babel/commit/15183078e6783db4d4d3deebba97e10b4fa68db3
[ 0.00017551631026435643, 0.00017283028864767402, 0.00017093696806114167, 0.00017203758761752397, 0.0000019517301552696154 ]
{ "id": 0, "code_window": [ " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: true,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " default: false,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts", "type": "replace", "edit_start_line_idx": 194 }
/** * 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 react/sort-prop-types */ import PropTypes from 'prop-types'; import React from 'react'; import { Histogram, BarSeries, XAxis, YAxis } from '@data-ui/histogram'; import { chartTheme } from '@data-ui/theme'; import { LegendOrdinal } from '@vx/legend'; import { scaleOrdinal } from '@vx/scale'; import { CategoricalColorNamespace, styled } from '@superset-ui/core'; import WithLegend from './WithLegend'; const propTypes = { className: PropTypes.string, data: PropTypes.arrayOf( PropTypes.shape({ key: PropTypes.string, values: PropTypes.arrayOf(PropTypes.number), }), ).isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, colorScheme: PropTypes.string, normalized: PropTypes.bool, binCount: PropTypes.number, opacity: PropTypes.number, xAxisLabel: PropTypes.string, yAxisLabel: PropTypes.string, }; const defaultProps = { binCount: 15, className: '', colorScheme: '', normalized: false, opacity: 1, xAxisLabel: '', yAxisLabel: '', }; class CustomHistogram extends React.PureComponent { render() { const { className, data, width, height, binCount, colorScheme, normalized, opacity, xAxisLabel, yAxisLabel, } = this.props; const colorFn = CategoricalColorNamespace.getScale(colorScheme); const keys = data.map(d => d.key); const colorScale = scaleOrdinal({ domain: keys, range: keys.map(x => colorFn(x)), }); return ( <WithLegend className={`superset-legacy-chart-histogram ${className}`} width={width} height={height} position="top" renderLegend={({ direction, style }) => ( <LegendOrdinal style={style} scale={colorScale} direction={direction} shape="rect" labelMargin="0 15px 0 0" /> )} renderChart={parent => ( <Histogram width={parent.width} height={parent.height} ariaLabel="Histogram" normalized={normalized} binCount={binCount} binType="numeric" margin={{ top: 20, right: 20 }} renderTooltip={({ datum, color }) => ( <div> <strong style={{ color }}> {datum.bin0} to {datum.bin1} </strong> <div> <strong>count </strong> {datum.count} </div> <div> <strong>cumulative </strong> {datum.cumulative} </div> </div> )} valueAccessor={datum => datum} theme={chartTheme} > {data.map(series => ( <BarSeries key={series.key} animated rawData={series.values} fill={colorScale(series.key)} fillOpacity={opacity} /> ))} <XAxis label={xAxisLabel} /> <YAxis label={yAxisLabel} /> </Histogram> )} /> ); } } CustomHistogram.propTypes = propTypes; CustomHistogram.defaultProps = defaultProps; export default styled(CustomHistogram)` .superset-legacy-chart-histogram { overflow: hidden; } `;
superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-histogram/src/Histogram.jsx
1
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.00019509289995767176, 0.00017154509259853512, 0.00016296155808959156, 0.00017114737420342863, 0.000007073794222378638 ]
{ "id": 0, "code_window": [ " type: 'CheckboxControl',\n", " label: t('Legend'),\n", " renderTrigger: true,\n", " default: true,\n", " description: t('Whether to display the legend (toggles)'),\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " default: false,\n" ], "file_path": "superset-frontend/temporary_superset_ui/superset-ui/plugins/legacy-plugin-chart-heatmap/src/controlPanel.ts", "type": "replace", "edit_start_line_idx": 194 }
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { Indicator } from 'src/dashboard/components/FiltersBadge/selectors'; import FilterIndicator from '.'; const createProps = () => ({ indicator: { column: 'product_category', name: 'Vaccine Approach', value: [] as any[], path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', ], } as Indicator, onClick: jest.fn(), }); test('Should render', () => { const props = createProps(); render(<FilterIndicator {...props} />); expect( screen.getByRole('button', { name: 'search Vaccine Approach' }), ).toBeInTheDocument(); expect(screen.getByRole('img', { name: 'search' })).toBeInTheDocument(); }); test('Should call "onClick"', () => { const props = createProps(); render(<FilterIndicator {...props} />); expect(props.onClick).toBeCalledTimes(0); userEvent.click( screen.getByRole('button', { name: 'search Vaccine Approach' }), ); expect(props.onClick).toBeCalledTimes(1); }); test('Should render "value"', () => { const props = createProps(); props.indicator.value = ['any', 'string']; render(<FilterIndicator {...props} />); expect( screen.getByRole('button', { name: 'search Vaccine Approach: any, string', }), ).toBeInTheDocument(); }); test('Should render with default props', () => { const props = createProps(); delete props.indicator.path; render(<FilterIndicator indicator={props.indicator} />); expect( screen.getByRole('button', { name: 'search Vaccine Approach' }), ).toBeInTheDocument(); userEvent.click( screen.getByRole('button', { name: 'search Vaccine Approach' }), ); });
superset-frontend/src/dashboard/components/FiltersBadge/FilterIndicator/FilterIndicator.test.tsx
0
https://github.com/apache/superset/commit/f0596103a86ec6a2d8496cdd526039674569c708
[ 0.0001741986779961735, 0.00017155735986307263, 0.00016902093193493783, 0.00017165222379844636, 0.0000014274031627792283 ]