UNPKG

@theia/core

Version:

Theia is a cloud & desktop IDE framework implemented in TypeScript.

302 lines • 14.5 kB
var DefaultSecondaryWindowService_1; import { __decorate } from "tslib"; // ***************************************************************************** // Copyright (C) 2022 STMicroelectronics, Ericsson, ARM, EclipseSource and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0. // // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License v. 2.0 are satisfied: GNU General Public License, version 2 // with the GNU Classpath Exception which is available at // https://www.gnu.org/software/classpath/license.html. // // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 // ***************************************************************************** import { inject, injectable, postConstruct, named } from 'inversify'; import { WindowService } from './window-service.js'; import { ExtractableWidget } from '../widgets/index.js'; import { Emitter, environment, PreferenceService, ILogger } from '../../common/index.js'; import { SaveableService } from '../saveable-service.js'; import { getAllWidgetsFromSecondaryWindow, getDefaultRestoreArea, SecondaryWindowHandler } from '../secondary-window-handler.js'; import { WindowFocusService } from './window-focus-service.js'; import { SecondaryWindowCloseContribution } from './secondary-window-close-contribution.js'; import { ContributionProvider } from '../../common/contribution-provider.js'; let DefaultSecondaryWindowService = class DefaultSecondaryWindowService { constructor() { this.onWindowOpenedEmitter = new Emitter; this.onWindowOpened = this.onWindowOpenedEmitter.event; this.onWindowLoadedEmitter = new Emitter; this.onWindowLoaded = this.onWindowLoadedEmitter.event; this.onWindowClosedEmitter = new Emitter; this.onWindowClosed = this.onWindowClosedEmitter.event; this.beforeWidgetRestoreEmitter = new Emitter; this.beforeWidgetRestore = this.beforeWidgetRestoreEmitter.event; /** * Randomized prefix to be included in opened windows' ids. * This avoids conflicts when creating sub-windows from multiple theia instances (e.g. by opening Theia multiple times in the same browser) */ this.prefix = crypto.getRandomValues(new Uint32Array(1))[0]; /** Unique id. Increase after every access. */ this.nextId = 0; this.secondaryWindows = []; /** * Whether the main window is shutting down, which closes all secondary windows. Such a close is not handled like a close by the user: * the widgets stay in their windows, so that the windows are stored with the layout and restored on the next start. */ this.shuttingDown = false; } static { DefaultSecondaryWindowService_1 = this; } // secondary-window.html is part of Theia's generated code. It is generated by dev-packages/application-manager/src/generator/frontend-generator.ts static { this.SECONDARY_WINDOW_URL = 'secondary-window.html'; } init() { // Set up messaging with secondary windows window.addEventListener('message', (event) => { this.logger.trace('Message on main window', event); if (event.data.fromSecondary) { this.logger.trace('Message comes from secondary window'); return; } if (event.data.fromMain) { this.logger.trace('Message has mainWindow marker, therefore ignore it'); return; } // Filter setImmediate messages. Do not forward because these come in with very high frequency. // They are not needed in secondary windows because these messages are just a work around // to make setImmediate work in the main window: https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate if (typeof event.data === 'string' && event.data.startsWith('setImmediate')) { return; } this.logger.trace('Delegate main window message to secondary windows', event); this.secondaryWindows.forEach(secondaryWindow => { if (!secondaryWindow.window.closed) { secondaryWindow.window.postMessage({ ...event.data, fromMain: true }, '*'); } }); }); this.registerShutdownListeners(); } registerShutdownListeners() { // Close all open windows when the main window is closed. this.windowService.onUnload(() => { this.shuttingDown = true; // Iterate backwards because calling window.close might remove the window from the array for (let i = this.secondaryWindows.length - 1; i >= 0; i--) { this.secondaryWindows[i].close(); } }); } createSecondaryWindow(widget, shell, options) { let [height, width, left, top] = options?.position ? [widget.node.clientHeight, widget.node.clientWidth, options.position.x, options.position.y] : this.findSecondaryWindowCoordinates(widget); if (options?.size) { ({ width, height } = options.size); } let features = `popup=1,width=${width},height=${height},left=${left},top=${top}`; if (this.preferenceService.get('window.secondaryWindowAlwaysOnTop')) { features += ',alwaysOnTop=true'; } const newWindow = window.open(DefaultSecondaryWindowService_1.SECONDARY_WINDOW_URL, this.nextWindowId(), features) ?? undefined; if (newWindow) { this.secondaryWindows.push(newWindow); this.onWindowOpenedEmitter.fire(newWindow); newWindow.addEventListener('DOMContentLoaded', () => { // This fires for the final secondary-window.html document, not for the initial // about:blank document the window starts out with, so onWindowLoaded listeners // can safely modify the document. this.onWindowLoadedEmitter.fire(newWindow); const focusRegistration = this.windowFocusService.registerWindow(newWindow); newWindow.addEventListener('beforeunload', evt => { if (this.shuttingDown) { // the main window has asked about unsaved changes already return; } const widgets = getAllWidgetsFromSecondaryWindow(newWindow) ?? [widget]; for (const w of widgets) { if (this.saveResourceService.wouldLoseChangesOnClose(w)) { evt.returnValue = ''; evt.preventDefault(); return 'non-empty'; } } }, { capture: true }); newWindow.addEventListener('pagehide', () => { focusRegistration.dispose(); const extIndex = this.secondaryWindows.indexOf(newWindow); if (extIndex > -1) { this.onWindowClosedEmitter.fire(newWindow); this.secondaryWindows.splice(extIndex, 1); } ; }); this.windowCreated(newWindow, widget, shell); }); newWindow.rootWidget = undefined; } return newWindow; } windowCreated(newWindow, widget, shell) { newWindow.addEventListener('pagehide', () => { this.restoreWidgets(newWindow, widget, shell); }); } findWindow(windowName) { for (const w of this.secondaryWindows) { if (w.name === windowName) { return w; } } return undefined; } findSecondaryWindowCoordinates(widget) { const clientBounds = widget.node.getBoundingClientRect(); const preference = this.preferenceService.get('window.secondaryWindowPlacement'); let height; let width; let left; let top; const offsetY = 20; // Offset to avoid the window title bar switch (preference) { case 'originalSize': { height = widget.node.clientHeight; width = widget.node.clientWidth; left = window.screenLeft + clientBounds.x; top = window.screenTop + (window.outerHeight - window.innerHeight) + offsetY; if (environment.electron.is()) { top = window.screenTop + clientBounds.y; } break; } case 'halfWidth': { height = window.innerHeight - (window.outerHeight - window.innerHeight); width = window.innerWidth / 2; left = window.screenLeft; top = window.screenTop; if (!environment.electron.is()) { height = window.innerHeight + clientBounds.y - offsetY; } break; } case 'fullSize': { height = window.innerHeight - (window.outerHeight - window.innerHeight); width = window.innerWidth; left = window.screenLeft; top = window.screenTop; if (!environment.electron.is()) { height = window.innerHeight + clientBounds.y - offsetY; } break; } } return [height, width, left, top]; } getWindows() { return this.secondaryWindows; } focus(win) { win.focus(); } nextWindowId() { return `${this.prefix}-secondaryWindow-${this.nextId++}`; } async restoreWidget(widget, secondaryWindow, shell) { const area = SecondaryWindowHandler.getMainWindowArea(ExtractableWidget.is(widget) ? widget.previousArea : getDefaultRestoreArea(secondaryWindow)); // fire removed event before adding it to shell this.beforeWidgetRestoreEmitter.fire([widget, secondaryWindow]); // reset ExtractableWidget properties before moving back so that handler evaluation is correct immediately if (ExtractableWidget.is(widget)) { widget.secondaryWindow = undefined; widget.previousArea = undefined; } await shell.addWidget(widget, { area }); // Don't wait for the widget to accept focus: while the secondary window is being closed, the main window may not // have focus yet, so waiting would delay closing the window until the activation times out. shell.activateWidget(widget.id); } /** * @returns whether the given widget is to be moved back to the main window instead of being closed with its secondary window */ async shouldRestoreOnClose(widget) { for (const contribution of this.closeContributions.getContributions()) { try { if (await contribution.shouldRestoreOnClose(widget)) { return true; } } catch (e) { this.logger.error('Failed to determine whether to move a widget back to the main window', e); return true; } } return false; } /** * Restore the widgets back to the main window, or close them, depending on the `window.secondaryWindowCloseBehavior` preference. * SecondaryWindowHandler needs to get informated about this. */ async restoreWidgets(newWindow, extractableWidget, shell) { if (this.shuttingDown) { // The widgets stay in the window, so that it is stored with the layout and restored with its widgets on the next start. return true; } // Copy, as moving a widget back removes it from the secondary window's widgets. // A window closed before it has been populated has no root widget, its widgets are still where they were. const widgets = [...getAllWidgetsFromSecondaryWindow(newWindow) ?? []]; const closeWidgets = this.preferenceService.get('window.secondaryWindowCloseBehavior', 'close') === 'close'; let allMovedOrDisposed = true; for (const widget of widgets) { if (widget.isDisposed) { continue; } try { if (closeWidgets && !await this.shouldRestoreOnClose(widget)) { await shell.closeWidget(widget.id); } // widgets that are not disposed when closed would be lost with the window if (!widget.isDisposed) { await this.restoreWidget(widget, newWindow, shell); } } catch (e) { // we can't move back, close instead // otherwise the window will just stay open with no way to close it await shell.closeWidget(widget.id); if (!widget.isDisposed) { allMovedOrDisposed = false; } } } return allMovedOrDisposed; } }; __decorate([ inject(WindowService) ], DefaultSecondaryWindowService.prototype, "windowService", void 0); __decorate([ inject(PreferenceService) ], DefaultSecondaryWindowService.prototype, "preferenceService", void 0); __decorate([ inject(SaveableService) ], DefaultSecondaryWindowService.prototype, "saveResourceService", void 0); __decorate([ inject(WindowFocusService) ], DefaultSecondaryWindowService.prototype, "windowFocusService", void 0); __decorate([ inject(ILogger), named('core:DefaultSecondaryWindowService') ], DefaultSecondaryWindowService.prototype, "logger", void 0); __decorate([ inject(ContributionProvider), named(SecondaryWindowCloseContribution) ], DefaultSecondaryWindowService.prototype, "closeContributions", void 0); __decorate([ postConstruct() ], DefaultSecondaryWindowService.prototype, "init", null); DefaultSecondaryWindowService = DefaultSecondaryWindowService_1 = __decorate([ injectable() ], DefaultSecondaryWindowService); export { DefaultSecondaryWindowService }; //# sourceMappingURL=default-secondary-window-service.js.map