status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
369
body
stringlengths
0
254k
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
4
188
file_content
stringlengths
0
5.12M
closed
electron/electron
https://github.com/electron/electron
38,137
[Docs] Wrong usage of ipcMain.handle in /tutorial-preload
This is a repost of #35157 . That issue is closed as fixed, but the merged pull request seems to fix a different unrelated issue. ### Steps to Reproduce: 1. Follow tutorial on macOS, including section "Open a window if none are open (macOS)" from [Part 2](https://www.electronjs.org/docs/latest/tutorial/tutorial-first-app#managing-your-apps-window-lifecycle). 2. Build and launch the app. 3. Close the window, open another window. ### Expected Behavior: - A new window launches without error. ### Actual Behavior: - An error is thrown and the window launches blank. ![image](https://user-images.githubusercontent.com/13035830/235337714-fc9496dc-b735-42b4-b981-9f8d8d72da55.png) This is because `icpMain.handle()` is being called every time a window is created (which can be multiple times on macOS) instead of just once (i.e. inside of `app.whenReady()`) https://github.com/electron/electron/blob/a2d35e9cf53f324d8153cb56982074e1af5fb177/docs/tutorial/tutorial-3-preload.md?plain=1#L209-L220
https://github.com/electron/electron/issues/38137
https://github.com/electron/electron/pull/38138
a8c0ed890f61664156886356ecb6ab9f73c69cf1
7f5364f98dd8d0b0baf4d6530ac23dbb5e2634df
2023-04-30T05:47:53Z
c++
2023-05-03T12:52:02Z
docs/tutorial/tutorial-3-preload.md
--- title: 'Using Preload Scripts' description: 'This guide will step you through the process of creating a barebones Hello World app in Electron, similar to electron/electron-quick-start.' slug: tutorial-preload hide_title: false --- :::info Follow along the tutorial This is **part 3** of the Electron tutorial. 1. [Prerequisites][prerequisites] 1. [Building your First App][building your first app] 1. **[Using Preload Scripts][preload]** 1. [Adding Features][features] 1. [Packaging Your Application][packaging] 1. [Publishing and Updating][updates] ::: ## Learning goals In this part of the tutorial, you will learn what a preload script is and how to use one to securely expose privileged APIs into the renderer process. You will also learn how to communicate between main and renderer processes with Electron's inter-process communication (IPC) modules. ## What is a preload script? Electron's main process is a Node.js environment that has full operating system access. On top of [Electron modules][modules], you can also access [Node.js built-ins][node-api], as well as any packages installed via npm. On the other hand, renderer processes run web pages and do not run Node.js by default for security reasons. To bridge Electron's different process types together, we will need to use a special script called a **preload**. ## Augmenting the renderer with a preload script A BrowserWindow's preload script runs in a context that has access to both the HTML DOM and a limited subset of Node.js and Electron APIs. :::info Preload script sandboxing From Electron 20 onwards, preload scripts are **sandboxed** by default and no longer have access to a full Node.js environment. Practically, this means that you have a polyfilled `require` function that only has access to a limited set of APIs. | Available API | Details | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Electron modules | Renderer process modules | | Node.js modules | [`events`](https://nodejs.org/api/events.html), [`timers`](https://nodejs.org/api/timers.html), [`url`](https://nodejs.org/api/url.html) | | Polyfilled globals | [`Buffer`](https://nodejs.org/api/buffer.html), [`process`](../api/process.md), [`clearImmediate`](https://nodejs.org/api/timers.html#timers_clearimmediate_immediate), [`setImmediate`](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args) | For more information, check out the [Process Sandboxing](./sandbox.md) guide. ::: Preload scripts are injected before a web page loads in the renderer, similar to a Chrome extension's [content scripts][content-script]. To add features to your renderer that require privileged access, you can define [global][] objects through the [contextBridge][contextbridge] API. To demonstrate this concept, you will create a preload script that exposes your app's versions of Chrome, Node, and Electron into the renderer. Add a new `preload.js` script that exposes selected properties of Electron's `process.versions` object to the renderer process in a `versions` global variable. ```js title="preload.js" const { contextBridge } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, // we can also expose variables, not just functions }) ``` To attach this script to your renderer process, pass its path to the `webPreferences.preload` option in the BrowserWindow constructor: ```js {2,8-10} title="main.js" const { app, BrowserWindow } = require('electron') const path = require('path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() }) ``` :::info There are two Node.js concepts that are used here: - The [`__dirname`][dirname] string points to the path of the currently executing script (in this case, your project's root folder). - The [`path.join`][path-join] API joins multiple path segments together, creating a combined path string that works across all platforms. ::: At this point, the renderer has access to the `versions` global, so let's display that information in the window. This variable can be accessed via `window.versions` or simply `versions`. Create a `renderer.js` script that uses the [`document.getElementById`][] DOM API to replace the displayed text for the HTML element with `info` as its `id` property. ```js title="renderer.js" const information = document.getElementById('info') information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})` ``` Then, modify your `index.html` by adding a new element with `info` as its `id` property, and attach your `renderer.js` script: ```html {18,20} title="index.html" <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <title>Hello from Electron renderer!</title> </head> <body> <h1>Hello from Electron renderer!</h1> <p>👋</p> <p id="info"></p> </body> <script src="./renderer.js"></script> </html> ``` After following the above steps, your app should look something like this: ![Electron app showing This app is using Chrome (v102.0.5005.63), Node.js (v16.14.2), and Electron (v19.0.3)](../images/preload-example.png) And the code should look like this: ```fiddle docs/fiddles/tutorial-preload ``` ## Communicating between processes As we have mentioned above, Electron's main and renderer process have distinct responsibilities and are not interchangeable. This means it is not possible to access the Node.js APIs directly from the renderer process, nor the HTML Document Object Model (DOM) from the main process. The solution for this problem is to use Electron's `ipcMain` and `ipcRenderer` modules for inter-process communication (IPC). To send a message from your web page to the main process, you can set up a main process handler with `ipcMain.handle` and then expose a function that calls `ipcRenderer.invoke` to trigger the handler in your preload script. To illustrate, we will add a global function to the renderer called `ping()` that will return a string from the main process. First, set up the `invoke` call in your preload script: ```js {1,7} title="preload.js" const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, ping: () => ipcRenderer.invoke('ping'), // we can also expose variables, not just functions }) ``` :::caution IPC security Notice how we wrap the `ipcRenderer.invoke('ping')` call in a helper function rather than expose the `ipcRenderer` module directly via context bridge. You **never** want to directly expose the entire `ipcRenderer` module via preload. This would give your renderer the ability to send arbitrary IPC messages to the main process, which becomes a powerful attack vector for malicious code. ::: Then, set up your `handle` listener in the main process. We do this _before_ loading the HTML file so that the handler is guaranteed to be ready before you send out the `invoke` call from the renderer. ```js {1,12} title="main.js" const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) ipcMain.handle('ping', () => 'pong') win.loadFile('index.html') } app.whenReady().then(createWindow) ``` Once you have the sender and receiver set up, you can now send messages from the renderer to the main process through the `'ping'` channel you just defined. ```js title='renderer.js' const func = async () => { const response = await window.versions.ping() console.log(response) // prints out 'pong' } func() ``` :::info For more in-depth explanations on using the `ipcRenderer` and `ipcMain` modules, check out the full [Inter-Process Communication][ipc] guide. ::: ## Summary A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node.js environment, and is often used to expose privileged APIs to the renderer via the `contextBridge` API. Because the main and renderer processes have very different responsibilities, Electron apps often use the preload script to set up inter-process communication (IPC) interfaces to pass arbitrary messages between the two kinds of processes. In the next part of the tutorial, we will be showing you resources on adding more functionality to your app, then teaching you distributing your app to users. <!-- Links --> [content-script]: https://developer.chrome.com/docs/extensions/mv3/content_scripts/ [contextbridge]: ../api/context-bridge.md [`document.getelementbyid`]: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById [dirname]: https://nodejs.org/api/modules.html#modules_dirname [global]: https://developer.mozilla.org/en-US/docs/Glossary/Global_object [ipc]: ./ipc.md [modules]: ../api/app.md [node-api]: https://nodejs.org/dist/latest/docs/api/ [path-join]: https://nodejs.org/api/path.html#path_path_join_paths <!-- Tutorial links --> [prerequisites]: tutorial-1-prerequisites.md [building your first app]: tutorial-2-first-app.md [preload]: tutorial-3-preload.md [features]: tutorial-4-adding-features.md [packaging]: tutorial-5-packaging.md [updates]: tutorial-6-publishing-updating.md
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
.markdownlint.json
{ "commands-show-output": false, "first-line-h1": false, "header-increment": false, "line-length": { "code_blocks": false, "tables": false, "stern": true, "line_length": -1 }, "no-bare-urls": false, "no-blanks-blockquote": false, "no-duplicate-header": { "allow_different_nesting": true }, "no-emphasis-as-header": false, "no-hard-tabs": { "code_blocks": false }, "no-space-in-emphasis": false, "no-trailing-punctuation": false, "no-trailing-spaces": { "br_spaces": 0 }, "single-h1": false, "no-inline-html": false }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
package.json
{ "name": "electron", "version": "0.0.0-development", "repository": "https://github.com/electron/electron", "description": "Build cross platform desktop apps with JavaScript, HTML, and CSS", "devDependencies": { "@azure/storage-blob": "^12.9.0", "@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4", "@electron/asar": "^3.2.1", "@electron/docs-parser": "^1.1.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^1.5.0", "@electron/typescript-definitions": "^8.14.0", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", "@types/basic-auth": "^1.1.3", "@types/busboy": "^1.5.0", "@types/chai": "^4.2.12", "@types/chai-as-promised": "^7.1.3", "@types/dirty-chai": "^2.0.2", "@types/express": "^4.17.13", "@types/fs-extra": "^9.0.1", "@types/klaw": "^3.0.1", "@types/minimist": "^1.2.0", "@types/mocha": "^7.0.2", "@types/node": "^18.11.18", "@types/semver": "^7.3.3", "@types/send": "^0.14.5", "@types/split": "^1.0.0", "@types/stream-json": "^1.5.1", "@types/temp": "^0.8.34", "@types/uuid": "^3.4.6", "@types/webpack": "^5.28.0", "@types/webpack-env": "^1.17.0", "@typescript-eslint/eslint-plugin": "^4.4.1", "@typescript-eslint/parser": "^4.4.1", "buffer": "^6.0.3", "check-for-leaks": "^1.2.1", "colors": "1.4.0", "dotenv-safe": "^4.0.4", "dugite": "^2.3.0", "eslint": "^7.4.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.22.0", "eslint-plugin-mocha": "^7.0.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-standard": "^4.0.1", "eslint-plugin-typescript": "^0.14.0", "events": "^3.2.0", "express": "^4.16.4", "folder-hash": "^2.1.1", "fs-extra": "^9.0.1", "got": "^11.8.5", "husky": "^8.0.1", "klaw": "^3.0.0", "lint": "^1.1.2", "lint-staged": "^10.2.11", "markdownlint-cli": "^0.33.0", "mdast-util-from-markdown": "^1.2.0", "minimist": "^1.2.6", "null-loader": "^4.0.0", "pre-flight": "^1.1.0", "process": "^0.11.10", "remark-cli": "^10.0.0", "remark-preset-lint-markdown-style-guide": "^4.0.0", "semver": "^5.6.0", "shx": "^0.3.2", "standard-markdown": "^6.0.0", "stream-json": "^1.7.1", "tap-xunit": "^2.4.1", "temp": "^0.8.3", "timers-browserify": "1.4.2", "ts-loader": "^8.0.2", "ts-node": "6.2.0", "typescript": "^4.5.5", "unist-util-visit": "^4.1.1", "url": "^0.11.0", "vscode-languageserver": "^8.0.2", "vscode-languageserver-textdocument": "^1.0.7", "vscode-uri": "^3.0.6", "webpack": "^5.76.0", "webpack-cli": "^4.10.0", "wrapper-webpack-plugin": "^2.2.0" }, "private": true, "scripts": { "asar": "asar", "generate-version-json": "node script/generate-version-json.js", "lint": "node ./script/lint.js && npm run lint:docs", "lint:js": "node ./script/lint.js --js", "lint:clang-format": "python3 script/run-clang-format.py -r -c shell/ || (echo \"\\nCode not formatted correctly.\" && exit 1)", "lint:clang-tidy": "ts-node ./script/run-clang-tidy.ts", "lint:cpp": "node ./script/lint.js --cc", "lint:objc": "node ./script/lint.js --objc", "lint:py": "node ./script/lint.js --py", "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-fiddles && npm run lint:docs-relative-links && npm run lint:markdownlint", "lint:docs-fiddles": "standard \"docs/fiddles/**/*.js\"", "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs", "create-api-json": "node script/create-api-json.js", "create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js", "gn-typescript-definitions": "npm run create-typescript-definitions && shx cp electron.d.ts", "pre-flight": "pre-flight", "gn-check": "node ./script/gn-check.js", "gn-format": "python3 script/run-gn-format.py", "precommit": "lint-staged", "preinstall": "node -e 'process.exit(0)'", "prepack": "check-for-leaks", "prepare": "husky install", "pretest": "npm run create-typescript-definitions", "repl": "node ./script/start.js --interactive", "start": "node ./script/start.js", "test": "node ./script/spec-runner.js", "tsc": "tsc", "webpack": "webpack" }, "license": "MIT", "author": "Electron Community", "keywords": [ "electron" ], "lint-staged": { "*.{js,ts}": [ "node script/lint.js --js --fix --only --" ], "*.{js,ts,d.ts}": [ "ts-node script/gen-filenames.ts" ], "*.{cc,mm,c,h}": [ "python3 script/run-clang-format.py -r -c --fix" ], "*.md": [ "npm run lint:docs" ], "*.{gn,gni}": [ "npm run gn-check", "npm run gn-format" ], "*.py": [ "node script/lint.js --py --fix --only --" ], "docs/api/**/*.md": [ "ts-node script/gen-filenames.ts", "markdownlint --config .markdownlint.autofix.json --fix", "git add filenames.auto.gni" ], "{*.patch,.patches}": [ "node script/lint.js --patches --only --", "ts-node script/check-patch-diff.ts" ], "DEPS": [ "node script/gen-hunspell-filenames.js", "node script/gen-libc++-filenames.js" ] }, "resolutions": { "nan": "nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac" } }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/lib/markdown.ts
import * as fs from 'fs'; import * as path from 'path'; import * as MarkdownIt from 'markdown-it'; import { githubSlugifier, resolveInternalDocumentLink, ExternalHref, FileStat, HrefKind, InternalHref, IMdLinkComputer, IMdParser, ITextDocument, IWorkspace, MdLink, MdLinkKind } from '@dsanders11/vscode-markdown-languageservice'; import { Emitter, Range } from 'vscode-languageserver'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { URI } from 'vscode-uri'; import { findMatchingFiles } from './utils'; import type { Definition, ImageReference, Link, LinkReference } from 'mdast'; import type { fromMarkdown as FromMarkdownFunction } from 'mdast-util-from-markdown'; import type { Node, Position } from 'unist'; import type { visit as VisitFunction } from 'unist-util-visit'; // Helper function to work around import issues with ESM modules and ts-node // eslint-disable-next-line no-new-func const dynamicImport = new Function('specifier', 'return import(specifier)'); // Helper function from `vscode-markdown-languageservice` codebase function tryDecodeUri (str: string): string { try { return decodeURI(str); } catch { return str; } } // Helper function from `vscode-markdown-languageservice` codebase function createHref ( sourceDocUri: URI, link: string, workspace: IWorkspace ): ExternalHref | InternalHref | undefined { if (/^[a-z-][a-z-]+:/i.test(link)) { // Looks like a uri return { kind: HrefKind.External, uri: URI.parse(tryDecodeUri(link)) }; } const resolved = resolveInternalDocumentLink(sourceDocUri, link, workspace); if (!resolved) { return undefined; } return { kind: HrefKind.Internal, path: resolved.resource, fragment: resolved.linkFragment }; } function positionToRange (position: Position): Range { return { start: { character: position.start.column - 1, line: position.start.line - 1 }, end: { character: position.end.column - 1, line: position.end.line - 1 } }; } const mdIt = MarkdownIt({ html: true }); export class MarkdownParser implements IMdParser { slugifier = githubSlugifier; async tokenize (document: TextDocument) { return mdIt.parse(document.getText(), {}); } } export class DocsWorkspace implements IWorkspace { private readonly documentCache: Map<string, TextDocument>; readonly root: string; constructor (root: string) { this.documentCache = new Map(); this.root = root; } get workspaceFolders () { return [URI.file(this.root)]; } async getAllMarkdownDocuments (): Promise<Iterable<ITextDocument>> { const files = await findMatchingFiles(this.root, (file) => file.endsWith('.md') ); for (const file of files) { const document = TextDocument.create( URI.file(file).toString(), 'markdown', 1, fs.readFileSync(file, 'utf8') ); this.documentCache.set(file, document); } return this.documentCache.values(); } hasMarkdownDocument (resource: URI) { const relativePath = path.relative(this.root, resource.path); return ( !relativePath.startsWith('..') && !path.isAbsolute(relativePath) && fs.existsSync(resource.path) ); } async openMarkdownDocument (resource: URI) { if (!this.documentCache.has(resource.path)) { const document = TextDocument.create( resource.toString(), 'markdown', 1, fs.readFileSync(resource.path, 'utf8') ); this.documentCache.set(resource.path, document); } return this.documentCache.get(resource.path); } async stat (resource: URI): Promise<FileStat | undefined> { if (this.hasMarkdownDocument(resource)) { const stats = fs.statSync(resource.path); return { isDirectory: stats.isDirectory() }; } return undefined; } async readDirectory (): Promise<Iterable<readonly [string, FileStat]>> { throw new Error('Not implemented'); } // // These events are defined to fulfill the interface, but are never emitted // by this implementation since it's not meant for watching a workspace // #onDidChangeMarkdownDocument = new Emitter<ITextDocument>(); onDidChangeMarkdownDocument = this.#onDidChangeMarkdownDocument.event; #onDidCreateMarkdownDocument = new Emitter<ITextDocument>(); onDidCreateMarkdownDocument = this.#onDidCreateMarkdownDocument.event; #onDidDeleteMarkdownDocument = new Emitter<URI>(); onDidDeleteMarkdownDocument = this.#onDidDeleteMarkdownDocument.event; } export class MarkdownLinkComputer implements IMdLinkComputer { private readonly workspace: IWorkspace; constructor (workspace: IWorkspace) { this.workspace = workspace; } async getAllLinks (document: ITextDocument): Promise<MdLink[]> { const { fromMarkdown } = (await dynamicImport( 'mdast-util-from-markdown' )) as { fromMarkdown: typeof FromMarkdownFunction }; const tree = fromMarkdown(document.getText()); const links = [ ...(await this.#getInlineLinks(document, tree)), ...(await this.#getReferenceLinks(document, tree)), ...(await this.#getLinkDefinitions(document, tree)) ]; return links; } async #getInlineLinks ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const documentUri = URI.parse(document.uri); const links: MdLink[] = []; visit( tree, (node) => node.type === 'link', (node: Node) => { const link = node as Link; const href = createHref(documentUri, link.url, this.workspace); if (href) { const range = positionToRange(link.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; const fragmentRange = undefined; links.push({ kind: MdLinkKind.Link, href, source: { hrefText: link.url, resource: documentUri, range, targetRange, hrefRange, fragmentRange, pathText: link.url.split('#')[0] } }); } } ); return links; } async #getReferenceLinks ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const links: MdLink[] = []; visit( tree, (node) => ['imageReference', 'linkReference'].includes(node.type), (node: Node) => { const link = node as ImageReference | LinkReference; const range = positionToRange(link.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; links.push({ kind: MdLinkKind.Link, href: { kind: HrefKind.Reference, ref: link.label! }, source: { hrefText: link.label!, resource: URI.parse(document.uri), range, targetRange, hrefRange, fragmentRange: undefined, pathText: link.label! } }); } ); return links; } async #getLinkDefinitions ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const documentUri = URI.parse(document.uri); const links: MdLink[] = []; visit( tree, (node) => node.type === 'definition', (node: Node) => { const definition = node as Definition; const href = createHref(documentUri, definition.url, this.workspace); if (href) { const range = positionToRange(definition.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; const fragmentRange = undefined; links.push({ kind: MdLinkKind.Definition, href, ref: { range, text: definition.label! }, source: { hrefText: definition.url, resource: documentUri, range, targetRange, hrefRange, fragmentRange, pathText: definition.url.split('#')[0] } }); } } ); return links; } }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/lint-docs-links.ts
#!/usr/bin/env ts-node import * as path from 'path'; import { createLanguageService, DiagnosticLevel, DiagnosticOptions, ILogger } from '@dsanders11/vscode-markdown-languageservice'; import * as minimist from 'minimist'; import fetch from 'node-fetch'; import { CancellationTokenSource } from 'vscode-languageserver'; import { URI } from 'vscode-uri'; import { DocsWorkspace, MarkdownLinkComputer, MarkdownParser } from './lib/markdown'; class NoOpLogger implements ILogger { log (): void {} } const diagnosticOptions: DiagnosticOptions = { ignoreLinks: [], validateDuplicateLinkDefinitions: DiagnosticLevel.error, validateFileLinks: DiagnosticLevel.error, validateFragmentLinks: DiagnosticLevel.error, validateMarkdownFileLinkFragments: DiagnosticLevel.error, validateReferences: DiagnosticLevel.error, validateUnusedLinkDefinitions: DiagnosticLevel.error }; async function fetchExternalLink (link: string, checkRedirects = false) { try { const response = await fetch(link); if (response.status !== 200) { console.log('Broken link', link, response.status, response.statusText); } else { if (checkRedirects && response.redirected) { const wwwUrl = new URL(link); wwwUrl.hostname = `www.${wwwUrl.hostname}`; // For now cut down on noise to find meaningful redirects const wwwRedirect = wwwUrl.toString() === response.url; const trailingSlashRedirect = `${link}/` === response.url; if (!wwwRedirect && !trailingSlashRedirect) { console.log('Link redirection', link, '->', response.url); } } return true; } } catch { console.log('Broken link', link); } return false; } async function main ({ fetchExternalLinks = false, checkRedirects = false }) { const workspace = new DocsWorkspace(path.resolve(__dirname, '..', 'docs')); const parser = new MarkdownParser(); const linkComputer = new MarkdownLinkComputer(workspace); const languageService = createLanguageService({ workspace, parser, logger: new NoOpLogger(), linkComputer }); const cts = new CancellationTokenSource(); let errors = false; const externalLinks = new Set<string>(); try { // Collect diagnostics for all documents in the workspace for (const document of await workspace.getAllMarkdownDocuments()) { for (let link of await languageService.getDocumentLinks( document, cts.token )) { if (link.target === undefined) { link = (await languageService.resolveDocumentLink(link, cts.token)) ?? link; } if ( link.target && link.target.startsWith('http') && new URL(link.target).hostname !== 'localhost' ) { externalLinks.add(link.target); } } const diagnostics = await languageService.computeDiagnostics( document, diagnosticOptions, cts.token ); if (diagnostics.length) { console.log( 'File Location:', path.relative(workspace.root, URI.parse(document.uri).path) ); } for (const diagnostic of diagnostics) { console.log( `\tBroken link on line ${diagnostic.range.start.line + 1}:`, diagnostic.message ); errors = true; } } } finally { cts.dispose(); } if (fetchExternalLinks) { const externalLinkStates = await Promise.all( Array.from(externalLinks).map((link) => fetchExternalLink(link, checkRedirects) ) ); errors = errors || !externalLinkStates.every((x) => x); } return errors; } function parseCommandLine () { const showUsage = (arg?: string): boolean => { if (!arg || arg.startsWith('-')) { console.log( 'Usage: script/lint-docs-links.ts [-h|--help] [--fetch-external-links] ' + '[--check-redirects]' ); process.exit(0); } return true; }; const opts = minimist(process.argv.slice(2), { boolean: ['help', 'fetch-external-links', 'check-redirects'], stopEarly: true, unknown: showUsage }); if (opts.help) showUsage(); return opts; } if (process.mainModule === module) { const opts = parseCommandLine(); main({ fetchExternalLinks: opts['fetch-external-links'], checkRedirects: opts['check-redirects'] }) .then((errors) => { if (errors) process.exit(1); }) .catch((error) => { console.error(error); process.exit(1); }); }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/markdownlint-emd001.js
const { addError, getLineMetadata, getReferenceLinkImageData } = require('markdownlint/helpers'); module.exports = { names: ['EMD001', 'no-shortcut-reference-links'], description: 'Disallow shortcut reference links (those with no link label)', tags: ['images', 'links'], function: function EMD001 (params, onError) { const lineMetadata = getLineMetadata(params); const { shortcuts } = getReferenceLinkImageData(lineMetadata); for (const [shortcut, occurrences] of shortcuts) { for (const [lineNumber] of occurrences) { addError( onError, lineNumber + 1, // human-friendly line numbers (1-based) `Disallowed shortcut reference link: "${shortcut}"` ); } } } };
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
yarn.lock
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@azure/abort-controller@^1.0.0": version "1.0.4" resolved "https://registry.yarnpkg.com/@azure/abort-controller/-/abort-controller-1.0.4.tgz#fd3c4d46c8ed67aace42498c8e2270960250eafd" integrity sha512-lNUmDRVGpanCsiUN3NWxFTdwmdFI53xwhkTFfHDGTYk46ca7Ind3nanJc+U6Zj9Tv+9nTCWRBscWEW1DyKOpTw== dependencies: tslib "^2.0.0" "@azure/core-asynciterator-polyfill@^1.0.0": version "1.0.2" resolved "https://registry.yarnpkg.com/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.2.tgz#0dd3849fb8d97f062a39db0e5cadc9ffaf861fec" integrity sha512-3rkP4LnnlWawl0LZptJOdXNrT/fHp2eQMadoasa6afspXdpGrtPZuAQc2PD0cpgyuoXtUWyC3tv7xfntjGS5Dw== "@azure/core-auth@^1.3.0": version "1.3.2" resolved "https://registry.yarnpkg.com/@azure/core-auth/-/core-auth-1.3.2.tgz#6a2c248576c26df365f6c7881ca04b7f6d08e3d0" integrity sha512-7CU6DmCHIZp5ZPiZ9r3J17lTKMmYsm/zGvNkjArQwPkrLlZ1TZ+EUYfGgh2X31OLMVAQCTJZW4cXHJi02EbJnA== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/core-http@^3.0.0": version "3.0.1" resolved "https://registry.yarnpkg.com/@azure/core-http/-/core-http-3.0.1.tgz#2177f3abb64afa8ca101dc34f67cc789888f9f7b" integrity sha512-A3x+um3cAPgQe42Lu7Iv/x8/fNjhL/nIoEfqFxfn30EyxK6zC13n+OUxzZBRC0IzQqssqIbt4INf5YG7lYYFtw== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-auth" "^1.3.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/core-util" "^1.1.1" "@azure/logger" "^1.0.0" "@types/node-fetch" "^2.5.0" "@types/tunnel" "^0.0.3" form-data "^4.0.0" node-fetch "^2.6.7" process "^0.11.10" tslib "^2.2.0" tunnel "^0.0.6" uuid "^8.3.0" xml2js "^0.5.0" "@azure/core-lro@^2.2.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-lro/-/core-lro-2.2.4.tgz#42fbf4ae98093c59005206a4437ddcd057c57ca1" integrity sha512-e1I2v2CZM0mQo8+RSix0x091Av493e4bnT22ds2fcQGslTHzM2oTbswkB65nP4iEpCxBrFxOSDPKExmTmjCVtQ== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" tslib "^2.2.0" "@azure/core-paging@^1.1.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@azure/core-paging/-/core-paging-1.2.1.tgz#1b884f563b6e49971e9a922da3c7a20931867b54" integrity sha512-UtH5iMlYsvg+nQYIl4UHlvvSrsBjOlRF4fs0j7mxd3rWdAStrKYrh2durOpHs5C9yZbVhsVDaisoyaf/lL1EVA== dependencies: "@azure/core-asynciterator-polyfill" "^1.0.0" tslib "^2.2.0" "@azure/[email protected]": version "1.0.0-preview.13" resolved "https://registry.yarnpkg.com/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz#55883d40ae2042f6f1e12b17dd0c0d34c536d644" integrity sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ== dependencies: "@opentelemetry/api" "^1.0.1" tslib "^2.2.0" "@azure/core-util@^1.1.1": version "1.3.1" resolved "https://registry.yarnpkg.com/@azure/core-util/-/core-util-1.3.1.tgz#e830b99231e2091a2dc9ed652fff1cda69ba6582" integrity sha512-pjfOUAb+MPLODhGuXot/Hy8wUgPD0UTqYkY3BiYcwEETrLcUCVM1t0roIvlQMgvn1lc48TGy5bsonsFpF862Jw== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/logger@^1.0.0": version "1.0.3" resolved "https://registry.yarnpkg.com/@azure/logger/-/logger-1.0.3.tgz#6e36704aa51be7d4a1bae24731ea580836293c96" integrity sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g== dependencies: tslib "^2.2.0" "@azure/storage-blob@^12.9.0": version "12.14.0" resolved "https://registry.yarnpkg.com/@azure/storage-blob/-/storage-blob-12.14.0.tgz#32d3e5fa3bb2a12d5d44b186aed11c8e78f00178" integrity sha512-g8GNUDpMisGXzBeD+sKphhH5yLwesB4JkHr1U6be/X3F+cAMcyGLPD1P89g2M7wbEtUJWoikry1rlr83nNRBzg== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-http" "^3.0.0" "@azure/core-lro" "^2.2.0" "@azure/core-paging" "^1.1.1" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" events "^3.0.0" tslib "^2.2.0" "@babel/code-frame@^7.0.0": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw== dependencies: "@babel/highlight" "^7.0.0" "@babel/highlight@^7.0.0": version "7.5.0" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540" integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ== dependencies: chalk "^2.0.0" esutils "^2.0.2" js-tokens "^4.0.0" "@discoveryjs/json-ext@^0.5.0": version "0.5.7" resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== "@dsanders11/vscode-markdown-languageservice@^0.3.0-alpha.4": version "0.3.0-alpha.4" resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0-alpha.4.tgz#cd80b82142a2c10e09b5f36a93c3ea65b7d2a7f9" integrity sha512-MHp/CniEkzJb1CAw/bHwucuImaICrcIuohEFamTW8sJC2jhKCnbYblwJFZ3OOS3wTYZbzFIa8WZ4Dn5yL2E7jg== dependencies: "@vscode/l10n" "^0.0.10" picomatch "^2.3.1" vscode-languageserver-textdocument "^1.0.5" vscode-languageserver-types "^3.17.1" vscode-uri "^3.0.3" "@electron/asar@^3.2.1": version "3.2.1" resolved "https://registry.yarnpkg.com/@electron/asar/-/asar-3.2.1.tgz#c4143896f3dd43b59a80a9c9068d76f77efb62ea" integrity sha512-hE2cQMZ5+4o7+6T2lUaVbxIzrOjZZfX7dB02xuapyYFJZEAiWTelq6J3mMoxzd0iONDvYLPVKecB5tyjIoVDVA== dependencies: chromium-pickle-js "^0.2.0" commander "^5.0.0" glob "^7.1.6" minimatch "^3.0.4" optionalDependencies: "@types/glob" "^7.1.1" "@electron/docs-parser@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.1.0.tgz#ba095def41746bde56bee731feaf22272bf0b765" integrity sha512-qrjIKJk8t4/xAYldDVNQgcF8zdAAuG260bzPxdh/xI3p/yddm61bftoct+Tx2crnWFnOfOkr6nGERsDknNiT8A== dependencies: "@types/markdown-it" "^12.0.0" chai "^4.2.0" chalk "^3.0.0" fs-extra "^8.1.0" lodash.camelcase "^4.3.0" markdown-it "^12.0.0" minimist "^1.2.0" ora "^4.0.3" pretty-ms "^5.1.0" "@electron/fiddle-core@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@electron/fiddle-core/-/fiddle-core-1.0.4.tgz#d28e330c4d88f3916269558a43d214c4312333af" integrity sha512-gjPz3IAHK+/f0N52cWVeTZpdgENJo3QHBGeGqMDHFUgzSBRTVyAr8z8Lw8wpu6Ocizs154Rtssn4ba1ysABgLA== dependencies: "@electron/get" "^2.0.0" debug "^4.3.3" env-paths "^2.2.1" extract-zip "^2.0.1" fs-extra "^10.0.0" getos "^3.2.1" node-fetch "^2.6.1" semver "^7.3.5" simple-git "^3.5.0" "@electron/get@^2.0.0": version "2.0.2" resolved "https://registry.yarnpkg.com/@electron/get/-/get-2.0.2.tgz#ae2a967b22075e9c25aaf00d5941cd79c21efd7e" integrity sha512-eFZVFoRXb3GFGd7Ak7W4+6jBl9wBtiZ4AaYOse97ej6mKj5tkyO0dUnUChs1IhJZtx1BENo4/p4WUTXpi6vT+g== dependencies: debug "^4.1.1" env-paths "^2.2.0" fs-extra "^8.1.0" got "^11.8.5" progress "^2.0.3" semver "^6.2.0" sumchecker "^3.0.1" optionalDependencies: global-agent "^3.0.0" "@electron/github-app-auth@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@electron/github-app-auth/-/github-app-auth-1.5.0.tgz#426e64ba50143417d9b68f2795a1b119cb62108b" integrity sha512-t6Za+3E7jdIf1CX06nNV/avZhqSXNEkCLJ1xeAt5FKU9HdGbjzwSfirM+UlHO7lMGyuf13BGCZOCB1kODhDLWQ== dependencies: "@octokit/auth-app" "^3.6.1" "@octokit/rest" "^18.12.0" "@electron/typescript-definitions@^8.14.0": version "8.14.0" resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.14.0.tgz#a88f74e915317ba943b57ffe499b319d04f01ee3" integrity sha512-J3b4is6L0NB4+r+7s1Hl1YlzaveKnQt1gswadRyMRwb4gFU3VAe2oBMJLOhFRJMs/9PK/Xp+y9QwyC92Tyqe6A== dependencies: "@types/node" "^11.13.7" chalk "^2.4.2" colors "^1.1.2" debug "^4.1.1" fs-extra "^7.0.1" lodash "^4.17.11" minimist "^1.2.0" mkdirp "^0.5.1" ora "^3.4.0" pretty-ms "^5.0.0" "@jridgewell/gen-mapping@^0.3.0": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== dependencies: "@jridgewell/set-array" "^1.0.1" "@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/resolve-uri@^3.0.3": version "3.1.0" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== "@jridgewell/source-map@^0.3.2": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== dependencies: "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== "@jridgewell/trace-mapping@^0.3.7", "@jridgewell/trace-mapping@^0.3.9": version "0.3.14" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz#b231a081d8f66796e475ad588a1ef473112701ed" integrity sha512-bJWEfQ9lPTvm3SneWwRFVLzrh6nhjwqw7TUFFBEMzwvg7t7PCDenf2lDwqo4NQXzdpgBXyFgDWnQA+2vkruksQ== dependencies: "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" "@kwsites/file-exists@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/file-exists/-/file-exists-1.1.1.tgz#ad1efcac13e1987d8dbaf235ef3be5b0d96faa99" integrity sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw== dependencies: debug "^4.1.1" "@kwsites/promise-deferred@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz#8ace5259254426ccef57f3175bc64ed7095ed919" integrity sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw== "@nodelib/[email protected]": version "2.1.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b" integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw== dependencies: "@nodelib/fs.stat" "2.0.3" run-parallel "^1.1.9" "@nodelib/[email protected]", "@nodelib/fs.stat@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3" integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA== "@nodelib/fs.walk@^1.2.3": version "1.2.4" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976" integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ== dependencies: "@nodelib/fs.scandir" "2.1.3" fastq "^1.6.0" "@octokit/auth-app@^3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@octokit/auth-app/-/auth-app-3.6.1.tgz#aa5b02cc211175cbc28ce6c03c73373c1206d632" integrity sha512-6oa6CFphIYI7NxxHrdVOzhG7hkcKyGyYocg7lNDSJVauVOLtylg8hNJzoUyPAYKKK0yUeoZamE/lMs2tG+S+JA== dependencies: "@octokit/auth-oauth-app" "^4.3.0" "@octokit/auth-oauth-user" "^1.2.3" "@octokit/request" "^5.6.0" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.0.3" "@types/lru-cache" "^5.1.0" deprecation "^2.3.1" lru-cache "^6.0.0" universal-github-app-jwt "^1.0.1" universal-user-agent "^6.0.0" "@octokit/auth-oauth-app@^4.3.0": version "4.3.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-app/-/auth-oauth-app-4.3.4.tgz#7030955b1a59d4d977904775c606477d95fcfe8e" integrity sha512-OYOTSSINeUAiLMk1uelaGB/dEkReBqHHr8+hBejzMG4z1vA4c7QSvDAS0RVZSr4oD4PEUPYFzEl34K7uNrXcWA== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/auth-oauth-user" "^2.0.0" "@octokit/request" "^5.6.3" "@octokit/types" "^6.0.3" "@types/btoa-lite" "^1.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^3.1.1": version "3.1.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-3.1.4.tgz#703c42f27a1e2eb23498a7001ad8e9ecf4a2f477" integrity sha512-6sHE/++r+aEFZ/BKXOGPJcH/nbgbBjS1A4CHfq/PbPEwb0kZEt43ykW98GBO/rYBPAYaNpCPvXfGwzgR9yMCXg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^6.10.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^4.0.0": version "4.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.3.tgz#00ce77233517e0d7d39e42a02652f64337d9df81" integrity sha512-KPTx5nMntKjNZzzltO3X4T68v22rd7Cp/TcLJXQE2U8aXPcZ9LFuww9q9Q5WUNSu3jwi3lRwzfkPguRfz1R8Vg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^1.2.3": version "1.3.0" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-1.3.0.tgz#da4e4529145181a6aa717ae858afb76ebd6e3360" integrity sha512-3QC/TAdk7onnxfyZ24BnJRfZv8TRzQK7SEFUS9vLng4Vv6Hv6I64ujdk/CUkREec8lhrwU764SZ/d+yrjjqhaQ== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/oauth-methods" "^1.1.0" "@octokit/request" "^5.4.14" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-2.0.4.tgz#88f060ec678d7d493695af8d827e115dd064e212" integrity sha512-HrbDzTPqz6GcGSOUkR+wSeF3vEqsb9NMsmPja/qqqdiGmlk/Czkxctc3KeWYogHonp62Ml4kjz2VxKawrFsadQ== dependencies: "@octokit/auth-oauth-device" "^4.0.0" "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-token@^2.4.4": version "2.5.0" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36" integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g== dependencies: "@octokit/types" "^6.0.3" "@octokit/auth-token@^3.0.0": version "3.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-3.0.3.tgz#ce7e48a3166731f26068d7a7a7996b5da58cbe0c" integrity sha512-/aFM2M4HVDBT/jjDBa84sJniv1t9Gm/rLkalaz9htOm+L+8JMj1k9w0CkUdcxNyNxZPlTxKPVko+m1VlM58ZVA== dependencies: "@octokit/types" "^9.0.0" "@octokit/core@^3.5.1": version "3.6.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.6.0.tgz#3376cb9f3008d9b3d110370d90e0a1fcd5fe6085" integrity sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q== dependencies: "@octokit/auth-token" "^2.4.4" "@octokit/graphql" "^4.5.8" "@octokit/request" "^5.6.3" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.0.3" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/core@^4.1.0": version "4.2.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-4.2.0.tgz#8c253ba9605aca605bc46187c34fcccae6a96648" integrity sha512-AgvDRUg3COpR82P7PBdGZF/NNqGmtMq2NiPqeSsDIeCfYFOZ9gddqWNQHnFdEUf+YwOj4aZYmJnlPp7OXmDIDg== dependencies: "@octokit/auth-token" "^3.0.0" "@octokit/graphql" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^9.0.0" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^6.0.1": version "6.0.5" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.5.tgz#43a6adee813c5ffd2f719e20cfd14a1fee7c193a" integrity sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ== dependencies: "@octokit/types" "^5.0.0" is-plain-object "^4.0.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^7.0.0": version "7.0.3" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-7.0.3.tgz#0b96035673a9e3bedf8bab8f7335de424a2147ed" integrity sha512-57gRlb28bwTsdNXq+O3JTQ7ERmBTuik9+LelgcLIVfYwf235VHbN9QNo4kXExtp/h8T423cR5iJThKtFYxC7Lw== dependencies: "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" universal-user-agent "^6.0.0" "@octokit/graphql@^4.5.8": version "4.8.0" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3" integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg== dependencies: "@octokit/request" "^5.6.0" "@octokit/types" "^6.0.3" universal-user-agent "^6.0.0" "@octokit/graphql@^5.0.0": version "5.0.5" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-5.0.5.tgz#a4cb3ea73f83b861893a6370ee82abb36e81afd2" integrity sha512-Qwfvh3xdqKtIznjX9lz2D458r7dJPP8l6r4GQkIdWQouZwHQK0mVT88uwiU2bdTU2OtT1uOlKpRciUWldpG0yQ== dependencies: "@octokit/request" "^6.0.0" "@octokit/types" "^9.0.0" universal-user-agent "^6.0.0" "@octokit/oauth-authorization-url@^4.3.1": version "4.3.3" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-4.3.3.tgz#6a6ef38f243086fec882b62744f39b517528dfb9" integrity sha512-lhP/t0i8EwTmayHG4dqLXgU+uPVys4WD/qUNvC+HfB1S1dyqULm5Yx9uKc1x79aP66U1Cb4OZeW8QU/RA9A4XA== "@octokit/oauth-authorization-url@^5.0.0": version "5.0.0" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz#029626ce87f3b31addb98cd0d2355c2381a1c5a1" integrity sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg== "@octokit/oauth-methods@^1.1.0": version "1.2.6" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-1.2.6.tgz#b9ac65e374b2cc55ee9dd8dcdd16558550438ea7" integrity sha512-nImHQoOtKnSNn05uk2o76om1tJWiAo4lOu2xMAHYsNr0fwopP+Dv+2MlGvaMMlFjoqVd3fF3X5ZDTKCsqgmUaQ== dependencies: "@octokit/oauth-authorization-url" "^4.3.1" "@octokit/request" "^5.4.14" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" "@octokit/oauth-methods@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-2.0.4.tgz#6abd9593ca7f91fe5068375a363bd70abd5516dc" integrity sha512-RDSa6XL+5waUVrYSmOlYROtPq0+cfwppP4VaQY/iIei3xlFb0expH6YNsxNrZktcLhJWSpm9uzeom+dQrXlS3A== dependencies: "@octokit/oauth-authorization-url" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" "@octokit/openapi-types@^12.11.0": version "12.11.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.11.0.tgz#da5638d64f2b919bca89ce6602d059f1b52d3ef0" integrity sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ== "@octokit/openapi-types@^14.0.0": version "14.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-14.0.0.tgz#949c5019028c93f189abbc2fb42f333290f7134a" integrity sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw== "@octokit/openapi-types@^16.0.0": version "16.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-16.0.0.tgz#d92838a6cd9fb4639ca875ddb3437f1045cc625e" integrity sha512-JbFWOqTJVLHZSUUoF4FzAZKYtqdxWu9Z5m2QQnOyEa04fOFljvyh7D3GYKbfuaSWisqehImiVIMG4eyJeP5VEA== "@octokit/plugin-paginate-rest@^2.16.8": version "2.21.3" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz#7f12532797775640dbb8224da577da7dc210c87e" integrity sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw== dependencies: "@octokit/types" "^6.40.0" "@octokit/plugin-paginate-rest@^6.0.0": version "6.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.0.0.tgz#f34b5a7d9416019126042cd7d7b811e006c0d561" integrity sha512-Sq5VU1PfT6/JyuXPyt04KZNVsFOSBaYOAq2QRZUwzVlI10KFvcbUo8lR258AAQL1Et60b0WuVik+zOWKLuDZxw== dependencies: "@octokit/types" "^9.0.0" "@octokit/plugin-request-log@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85" integrity sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA== "@octokit/plugin-rest-endpoint-methods@^5.12.0": version "5.16.2" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz#7ee8bf586df97dd6868cf68f641354e908c25342" integrity sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw== dependencies: "@octokit/types" "^6.39.0" deprecation "^2.3.1" "@octokit/plugin-rest-endpoint-methods@^7.0.0": version "7.0.1" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.0.1.tgz#f7ebe18144fd89460f98f35a587b056646e84502" integrity sha512-pnCaLwZBudK5xCdrR823xHGNgqOzRnJ/mpC/76YPpNP7DybdsJtP7mdOwh+wYZxK5jqeQuhu59ogMI4NRlBUvA== dependencies: "@octokit/types" "^9.0.0" deprecation "^2.3.1" "@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0": version "2.1.0" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677" integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg== dependencies: "@octokit/types" "^6.0.3" deprecation "^2.0.0" once "^1.4.0" "@octokit/request-error@^3.0.0": version "3.0.2" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-3.0.2.tgz#f74c0f163d19463b87528efe877216c41d6deb0a" integrity sha512-WMNOFYrSaX8zXWoJg9u/pKgWPo94JXilMLb2VManNOby9EZxrQaBe/QSC4a1TzpAlpxofg2X/jMnCyZgL6y7eg== dependencies: "@octokit/types" "^8.0.0" deprecation "^2.0.0" once "^1.4.0" "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3": version "5.6.3" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0" integrity sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A== dependencies: "@octokit/endpoint" "^6.0.1" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.16.1" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/request@^6.0.0": version "6.2.2" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.2.tgz#a2ba5ac22bddd5dcb3f539b618faa05115c5a255" integrity sha512-6VDqgj0HMc2FUX2awIs+sM6OwLgwHvAi4KCK3mT2H2IKRt6oH9d0fej5LluF5mck1lRR/rFWN0YIDSYXYSylbw== dependencies: "@octokit/endpoint" "^7.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/rest@^18.12.0": version "18.12.0" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881" integrity sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q== dependencies: "@octokit/core" "^3.5.1" "@octokit/plugin-paginate-rest" "^2.16.8" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^5.12.0" "@octokit/rest@^19.0.7": version "19.0.7" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.7.tgz#d2e21b4995ab96ae5bfae50b4969da7e04e0bb70" integrity sha512-HRtSfjrWmWVNp2uAkEpQnuGMJsu/+dBr47dRc5QVgsCbnIc1+GFEaoKBWkYG+zjrsHpSqcAElMio+n10c0b5JA== dependencies: "@octokit/core" "^4.1.0" "@octokit/plugin-paginate-rest" "^6.0.0" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^7.0.0" "@octokit/types@^5.0.0": version "5.2.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.2.0.tgz#d075dc23bf293f540739250b6879e2c1be2fc20c" integrity sha512-XjOk9y4m8xTLIKPe1NFxNWBdzA2/z3PFFA/bwf4EoH6oS8hM0Y46mEa4Cb+KCyj/tFDznJFahzQ0Aj3o1FYq4A== dependencies: "@types/node" ">= 8" "@octokit/types@^6.0.3", "@octokit/types@^6.10.0", "@octokit/types@^6.12.2", "@octokit/types@^6.16.1", "@octokit/types@^6.39.0", "@octokit/types@^6.40.0": version "6.41.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.41.0.tgz#e58ef78d78596d2fb7df9c6259802464b5f84a04" integrity sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg== dependencies: "@octokit/openapi-types" "^12.11.0" "@octokit/types@^8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-8.0.0.tgz#93f0b865786c4153f0f6924da067fe0bb7426a9f" integrity sha512-65/TPpOJP1i3K4lBJMnWqPUJ6zuOtzhtagDvydAWbEXpbFYA0oMKKyLb95NFZZP0lSh/4b6K+DQlzvYQJQQePg== dependencies: "@octokit/openapi-types" "^14.0.0" "@octokit/types@^9.0.0": version "9.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-9.0.0.tgz#6050db04ddf4188ec92d60e4da1a2ce0633ff635" integrity sha512-LUewfj94xCMH2rbD5YJ+6AQ4AVjFYTgpp6rboWM5T7N3IsIF65SBEOVcYMGAEzO/kKNiNaW4LoWtoThOhH06gw== dependencies: "@octokit/openapi-types" "^16.0.0" "@opentelemetry/api@^1.0.1": version "1.0.4" resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.0.4.tgz#a167e46c10d05a07ab299fc518793b0cff8f6924" integrity sha512-BuJuXRSJNQ3QoKA6GWWDyuLpOUck+9hAXNMCnrloc1aWVoy6Xq6t9PUV08aBZ4Lutqq2LEHM486bpZqoViScog== "@primer/octicons@^10.0.0": version "10.0.0" resolved "https://registry.yarnpkg.com/@primer/octicons/-/octicons-10.0.0.tgz#81e94ed32545dfd3472c8625a5b345f3ea4c153d" integrity sha512-iuQubq62zXZjPmaqrsfsCZUqIJgZhmA6W0tKzIKGRbkoLnff4TFFCL87hfIRATZ5qZPM4m8ioT8/bXI7WVa9WQ== dependencies: object-assign "^4.1.1" "@sindresorhus/is@^4.0.0": version "4.6.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" integrity sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw== "@szmarczak/http-timer@^4.0.5": version "4.0.6" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-4.0.6.tgz#b4a914bb62e7c272d4e5989fe4440f812ab1d807" integrity sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w== dependencies: defer-to-connect "^2.0.0" "@types/basic-auth@^1.1.3": version "1.1.3" resolved "https://registry.yarnpkg.com/@types/basic-auth/-/basic-auth-1.1.3.tgz#a787ede8310804174fbbf3d6c623ab1ccedb02cd" integrity sha512-W3rv6J0IGlxqgE2eQ2pTb0gBjaGtejQpJ6uaCjz3UQ65+TFTPC5/lAE+POfx1YLdjtxvejJzsIAfd3MxWiVmfg== dependencies: "@types/node" "*" "@types/body-parser@*": version "1.19.0" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.0.tgz#0685b3c47eb3006ffed117cdd55164b61f80538f" integrity sha512-W98JrE0j2K78swW4ukqMleo8R7h/pFETjM2DQ90MF6XK2i4LO4W3gQ71Lt4w3bfm2EvVSyWHplECvB5sK22yFQ== dependencies: "@types/connect" "*" "@types/node" "*" "@types/btoa-lite@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/btoa-lite/-/btoa-lite-1.0.0.tgz#e190a5a548e0b348adb0df9ac7fa5f1151c7cca4" integrity sha512-wJsiX1tosQ+J5+bY5LrSahHxr2wT+uME5UDwdN1kg4frt40euqA+wzECkmq4t5QbveHiJepfdThgQrPw6KiSlg== "@types/busboy@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@types/busboy/-/busboy-1.5.0.tgz#62681556cbbd2afc8d2efa6bafaa15602f0838b9" integrity sha512-ncOOhwmyFDW76c/Tuvv9MA9VGYUCn8blzyWmzYELcNGDb0WXWLSmFi7hJq25YdRBYJrmMBB5jZZwUjlJe9HCjQ== dependencies: "@types/node" "*" "@types/cacheable-request@^6.0.1": version "6.0.2" resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.2.tgz#c324da0197de0a98a2312156536ae262429ff6b9" integrity sha512-B3xVo+dlKM6nnKTcmm5ZtY/OL8bOAOd2Olee9M1zft65ox50OzjEHW91sDiU9j6cvW8Ejg1/Qkf4xd2kugApUA== dependencies: "@types/http-cache-semantics" "*" "@types/keyv" "*" "@types/node" "*" "@types/responselike" "*" "@types/chai-as-promised@*": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.1.tgz#004c27a4ac640e9590e25d8b0980cb0a6609bfd8" integrity sha512-dberBxQW/XWv6BMj0su1lV9/C9AUx5Hqu2pisuS6S4YK/Qt6vurcj/BmcbEsobIWWCQzhesNY8k73kIxx4X7Mg== dependencies: "@types/chai" "*" "@types/chai-as-promised@^7.1.3": version "7.1.3" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.3.tgz#779166b90fda611963a3adbfd00b339d03b747bd" integrity sha512-FQnh1ohPXJELpKhzjuDkPLR2BZCAqed+a6xV4MI/T3XzHfd2FlarfUGUdZYgqYe8oxkYn0fchHEeHfHqdZ96sg== dependencies: "@types/chai" "*" "@types/chai@*": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.1.7.tgz#1b8e33b61a8c09cbe1f85133071baa0dbf9fa71a" integrity sha512-2Y8uPt0/jwjhQ6EiluT0XCri1Dbplr0ZxfFXUz+ye13gaqE8u5gL5ppao1JrUYr9cIip5S6MvQzBS7Kke7U9VA== "@types/chai@^4.2.12": version "4.2.12" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.2.12.tgz#6160ae454cd89dae05adc3bb97997f488b608201" integrity sha512-aN5IAC8QNtSUdQzxu7lGBgYAOuU1tmRU4c9dIq5OKGf/SBVjXo+ffM2wEjudAWbgpOhy60nLoAGH1xm8fpCKFQ== "@types/color-name@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== "@types/concat-stream@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/concat-stream/-/concat-stream-1.6.1.tgz#24bcfc101ecf68e886aaedce60dfd74b632a1b74" integrity sha512-eHE4cQPoj6ngxBZMvVf6Hw7Mh4jMW4U9lpGmS5GBPB9RYxlFg+CHaVN7ErNY4W9XfLIEn20b4VDYaIrbq0q4uA== dependencies: "@types/node" "*" "@types/connect@*": version "3.4.33" resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.33.tgz#31610c901eca573b8713c3330abc6e6b9f588546" integrity sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A== dependencies: "@types/node" "*" "@types/debug@^4.0.0": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg== dependencies: "@types/ms" "*" "@types/dirty-chai@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@types/dirty-chai/-/dirty-chai-2.0.2.tgz#eeac4802329a41ed7815ac0c1a6360335bf77d0c" integrity sha512-BruwIN/UQEU0ePghxEX+OyjngpOfOUKJQh3cmfeq2h2Su/g001iljVi3+Y2y2EFp3IPgjf4sMrRU33Hxv1FUqw== dependencies: "@types/chai" "*" "@types/chai-as-promised" "*" "@types/eslint-scope@^3.7.3": version "3.7.4" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16" integrity sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA== dependencies: "@types/eslint" "*" "@types/estree" "*" "@types/eslint@*": version "8.4.5" resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.4.5.tgz#acdfb7dd36b91cc5d812d7c093811a8f3d9b31e4" integrity sha512-dhsC09y1gpJWnK+Ff4SGvCuSnk9DaU0BJZSzOwa6GVSg65XtTugLBITDAAzRU5duGBoXBHpdR/9jHGxJjNflJQ== dependencies: "@types/estree" "*" "@types/json-schema" "*" "@types/estree@*": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.0.tgz#5fb2e536c1ae9bf35366eed879e827fa59ca41c2" integrity sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ== "@types/estree@^0.0.51": version "0.0.51" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== "@types/events@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" integrity sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig== dependencies: "@types/node" "*" "@types/qs" "*" "@types/range-parser" "*" "@types/express@^4.17.13": version "4.17.13" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.13.tgz#a76e2995728999bab51a33fabce1d705a3709034" integrity sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA== dependencies: "@types/body-parser" "*" "@types/express-serve-static-core" "^4.17.18" "@types/qs" "*" "@types/serve-static" "*" "@types/fs-extra@^9.0.1": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.1.tgz#91c8fc4c51f6d5dbe44c2ca9ab09310bd00c7918" integrity sha512-B42Sxuaz09MhC3DDeW5kubRcQ5by4iuVQ0cRRWM2lggLzAa/KVom0Aft/208NgMvNQQZ86s5rVcqDdn/SH0/mg== dependencies: "@types/node" "*" "@types/glob@^7.1.1": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" integrity sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w== dependencies: "@types/events" "*" "@types/minimatch" "*" "@types/node" "*" "@types/http-cache-semantics@*": version "4.0.1" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ== "@types/is-empty@^1.0.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/is-empty/-/is-empty-1.2.0.tgz#16bc578060c9b0b6953339eea906c255a375bf86" integrity sha512-brJKf2boFhUxTDxlpI7cstwiUtA2ovm38UzFTi9aZI6//ARncaV+Q5ALjCaJqXaMtdZk/oPTJnSutugsZR6h8A== "@types/js-yaml@^4.0.0": version "4.0.2" resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-4.0.2.tgz#4117a7a378593a218e9d6f0ef44ce6d5d9edf7fa" integrity sha512-KbeHS/Y4R+k+5sWXEYzAZKuB1yQlZtEghuhRxrVRLaqhtoG5+26JwQsa4HyS3AWX8v1Uwukma5HheduUDskasA== "@types/json-buffer@~3.0.0": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/json-buffer/-/json-buffer-3.0.0.tgz#85c1ff0f0948fc159810d4b5be35bf8c20875f64" integrity sha512-3YP80IxxFJB4b5tYC2SUPwkg0XQLiu0nWvhRgEatgjf+29IcWO9X1k8xRv5DGssJ/lCrjYTjQPcobJr2yWIVuQ== "@types/json-schema@*", "@types/json-schema@^7.0.8": version "7.0.11" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== "@types/json-schema@^7.0.3": version "7.0.3" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.3.tgz#bdfd69d61e464dcc81b25159c270d75a73c1a636" integrity sha512-Il2DtDVRGDcqjDtE+rF8iqg1CArehSK84HZJCT7AMITlyXRBpuPhqGLDQMowraqqu1coEaimg4ZOqggt6L6L+A== "@types/json-schema@^7.0.4": version "7.0.4" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339" integrity sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA== "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= "@types/jsonwebtoken@^9.0.0": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz#29b1369c4774200d6d6f63135bf3d1ba3ef997a4" integrity sha512-c5ltxazpWabia/4UzhIoaDcIza4KViOQhdbjRlfcIGVnsE3c3brkz9Z+F/EeJIECOQP7W7US2hNE930cWWkPiw== dependencies: "@types/node" "*" "@types/keyv@*": version "3.1.4" resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.4.tgz#3ccdb1c6751b0c7e52300bcdacd5bcbf8faa75b6" integrity sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg== dependencies: "@types/node" "*" "@types/klaw@^3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@types/klaw/-/klaw-3.0.1.tgz#29f90021c0234976aa4eb97efced9cb6db9fa8b3" integrity sha512-acnF3n9mYOr1aFJKFyvfNX0am9EtPUsYPq22QUCGdJE+MVt6UyAN1jwo+PmOPqXD4K7ZS9MtxDEp/un0lxFccA== dependencies: "@types/node" "*" "@types/linkify-it@*": version "2.1.0" resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-2.1.0.tgz#ea3dd64c4805597311790b61e872cbd1ed2cd806" integrity sha512-Q7DYAOi9O/+cLLhdaSvKdaumWyHbm7HAk/bFwwyTuU0arR5yyCeW5GOoqt4tJTpDRxhpx9Q8kQL6vMpuw9hDSw== "@types/lru-cache@^5.1.0": version "5.1.0" resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-5.1.0.tgz#57f228f2b80c046b4a1bd5cac031f81f207f4f03" integrity sha512-RaE0B+14ToE4l6UqdarKPnXwVDuigfFv+5j9Dze/Nqr23yyuqdNvzcZi3xB+3Agvi5R4EOgAksfv3lXX4vBt9w== "@types/markdown-it@^12.0.0": version "12.2.3" resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51" integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ== dependencies: "@types/linkify-it" "*" "@types/mdurl" "*" "@types/mdast@^3.0.0": version "3.0.7" resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.7.tgz#cba63d0cc11eb1605cea5c0ad76e02684394166b" integrity sha512-YwR7OK8aPmaBvMMUi+pZXBNoW2unbVbfok4YRqGMJBe1dpDlzpRkJrYEYmvjxgs5JhuQmKfDexrN98u941Zasg== dependencies: "@types/unist" "*" "@types/mdurl@*": version "1.0.2" resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9" integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA== "@types/mime@*": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-2.0.1.tgz#dc488842312a7f075149312905b5e3c0b054c79d" integrity sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw== "@types/mime@^1": version "1.3.2" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a" integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw== "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/minimist@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= "@types/mocha@^7.0.2": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-7.0.2.tgz#b17f16cf933597e10d6d78eae3251e692ce8b0ce" integrity sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w== "@types/ms@*": version "0.7.31" resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197" integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA== "@types/node-fetch@^2.5.0": version "2.6.1" resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.1.tgz#8f127c50481db65886800ef496f20bbf15518975" integrity sha512-oMqjURCaxoSIsHSr1E47QHzbmzNR5rK8McHuNb11BOM9cHcIK3Avy0s/b2JlXHoQGTYS3NsvWzV1M0iK7l0wbA== dependencies: "@types/node" "*" form-data "^3.0.0" "@types/node@*": version "12.6.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.1.tgz#d5544f6de0aae03eefbb63d5120f6c8be0691946" integrity sha512-rp7La3m845mSESCgsJePNL/JQyhkOJA6G4vcwvVgkDAwHhGdq5GCumxmPjEk1MZf+8p5ZQAUE7tqgQRQTXN7uQ== "@types/node@>= 8": version "14.0.27" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.27.tgz#a151873af5a5e851b51b3b065c9e63390a9e0eb1" integrity sha512-kVrqXhbclHNHGu9ztnAwSncIgJv/FaxmzXJvGXNdcCpV1b8u1/Mi6z6m0vwy0LzKeXFTPLH0NzwmoJ3fNCIq0g== "@types/node@^11.13.7": version "11.13.22" resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.22.tgz#91ee88ebfa25072433497f6f3150f84fa8c3a91b" integrity sha512-rOsaPRUGTOXbRBOKToy4cgZXY4Y+QSVhxcLwdEveozbk7yuudhWMpxxcaXqYizLMP3VY7OcWCFtx9lGFh5j5kg== "@types/node@^16.0.0": version "16.4.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d" integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg== "@types/node@^18.11.18": version "18.11.18" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.18.tgz#8dfb97f0da23c2293e554c5a50d61ef134d7697f" integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA== "@types/parse-json@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== "@types/qs@*": version "6.9.3" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" integrity sha512-7s9EQWupR1fTc2pSMtXRQ9w9gLOcrJn+h7HOXw4evxyvVqMi4f+q7d2tnFe3ng3SNHjtK+0EzGMGFUQX4/AQRA== "@types/range-parser@*": version "1.2.3" resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c" integrity sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA== "@types/repeat-string@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/repeat-string/-/repeat-string-1.6.1.tgz#8bb5686e662ce1d962271b0b043623bf51404cdc" integrity sha512-vdna8kjLGljgtPnYN6MBD2UwX62QE0EFLj9QlLXvg6dEu66NksXB900BNguBCMZZY2D9SSqncUskM23vT3uvWQ== "@types/responselike@*", "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA== dependencies: "@types/node" "*" "@types/semver@^7.3.3": version "7.3.3" resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.3.tgz#3ad6ed949e7487e7bda6f886b4a2434a2c3d7b1a" integrity sha512-jQxClWFzv9IXdLdhSaTf16XI3NYe6zrEbckSpb5xhKfPbWgIyAY0AFyWWWfaiDcBuj3UHmMkCIwSRqpKMTZL2Q== "@types/send@^0.14.5": version "0.14.5" resolved "https://registry.yarnpkg.com/@types/send/-/send-0.14.5.tgz#653f7d25b93c3f7f51a8994addaf8a229de022a7" integrity sha512-0mwoiK3DXXBu0GIfo+jBv4Wo5s1AcsxdpdwNUtflKm99VEMvmBPJ+/NBNRZy2R5JEYfWL/u4nAHuTUTA3wFecQ== dependencies: "@types/mime" "*" "@types/node" "*" "@types/serve-static@*": version "1.13.10" resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.13.10.tgz#f5e0ce8797d2d7cc5ebeda48a52c96c4fa47a8d9" integrity sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ== dependencies: "@types/mime" "^1" "@types/node" "*" "@types/split@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/split/-/split-1.0.0.tgz#24f7c35707450b002f203383228f5a2bc1e6c228" integrity sha512-pm9S1mkr+av0j7D6pFyqhBxXDbnbO9gqj4nb8DtGtCewvj0XhIv089SSwXrjrIizT1UquO8/h83hCut0pa3u8A== dependencies: "@types/node" "*" "@types/through" "*" "@types/stream-chain@*": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/stream-chain/-/stream-chain-2.0.0.tgz#aed7fc21ac3686bc721aebbbd971f5a857e567e4" integrity sha512-O3IRJcZi4YddlS8jgasH87l+rdNmad9uPAMmMZCfRVhumbWMX6lkBWnIqr9kokO5sx8LHp8peQ1ELhMZHbR0Gg== dependencies: "@types/node" "*" "@types/stream-json@^1.5.1": version "1.5.1" resolved "https://registry.yarnpkg.com/@types/stream-json/-/stream-json-1.5.1.tgz#ae8d1133f9f920e18c6e94b233cb57d014a47b8d" integrity sha512-Blg6GJbKVEB1J/y/2Tv+WrYiMzPTIqyuZ+zWDJtAF8Mo8A2XQh/lkSX4EYiM+qtS+GY8ThdGi6gGA9h4sjvL+g== dependencies: "@types/node" "*" "@types/stream-chain" "*" "@types/supports-color@^8.0.0": version "8.1.1" resolved "https://registry.yarnpkg.com/@types/supports-color/-/supports-color-8.1.1.tgz#1b44b1b096479273adf7f93c75fc4ecc40a61ee4" integrity sha512-dPWnWsf+kzIG140B8z2w3fr5D03TLWbOAFQl45xUpI3vcizeXriNR5VYkWZ+WTMsUHqZ9Xlt3hrxGNANFyNQfw== "@types/temp@^0.8.34": version "0.8.34" resolved "https://registry.yarnpkg.com/@types/temp/-/temp-0.8.34.tgz#03e4b3cb67cbb48c425bbf54b12230fef85540ac" integrity sha512-oLa9c5LHXgS6UimpEVp08De7QvZ+Dfu5bMQuWyMhf92Z26Q10ubEMOWy9OEfUdzW7Y/sDWVHmUaLFtmnX/2j0w== dependencies: "@types/node" "*" "@types/text-table@^0.2.0": version "0.2.2" resolved "https://registry.yarnpkg.com/@types/text-table/-/text-table-0.2.2.tgz#774c90cfcfbc8b4b0ebb00fecbe861dc8b1e8e26" integrity sha512-dGoI5Af7To0R2XE8wJuc6vwlavWARsCh3UKJPjWs1YEqGUqfgBI/j/4GX0yf19/DsDPPf0YAXWAp8psNeIehLg== "@types/through@*": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/through/-/through-0.0.29.tgz#72943aac922e179339c651fa34a4428a4d722f93" integrity sha512-9a7C5VHh+1BKblaYiq+7Tfc+EOmjMdZaD1MYtkQjSoxgB69tBjW98ry6SKsi4zEIWztLOMRuL87A3bdT/Fc/4w== dependencies: "@types/node" "*" "@types/tunnel@^0.0.3": version "0.0.3" resolved "https://registry.yarnpkg.com/@types/tunnel/-/tunnel-0.0.3.tgz#f109e730b072b3136347561fc558c9358bb8c6e9" integrity sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA== dependencies: "@types/node" "*" "@types/unist@*", "@types/unist@^2.0.0": version "2.0.6" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== "@types/unist@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e" integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ== "@types/uuid@^3.4.6": version "3.4.6" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.6.tgz#d2c4c48eb85a757bf2927f75f939942d521e3016" integrity sha512-cCdlC/1kGEZdEglzOieLDYBxHsvEOIg7kp/2FYyVR9Pxakq+Qf/inL3RKQ+PA8gOlI/NnL+fXmQH12nwcGzsHw== dependencies: "@types/node" "*" "@types/webpack-env@^1.17.0": version "1.17.0" resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0" integrity sha512-eHSaNYEyxRA5IAG0Ym/yCyf86niZUIF/TpWKofQI/CVfh5HsMEUyfE2kwFxha4ow0s5g0LfISQxpDKjbRDrizw== "@types/webpack@^5.28.0": version "5.28.0" resolved "https://registry.yarnpkg.com/@types/webpack/-/webpack-5.28.0.tgz#78dde06212f038d77e54116cfe69e88ae9ed2c03" integrity sha512-8cP0CzcxUiFuA9xGJkfeVpqmWTk9nx6CWwamRGCj95ph1SmlRRk9KlCZ6avhCbZd4L68LvYT6l1kpdEnQXrF8w== dependencies: "@types/node" "*" tapable "^2.2.0" webpack "^5" "@types/yauzl@^2.9.1": version "2.10.0" resolved "https://registry.yarnpkg.com/@types/yauzl/-/yauzl-2.10.0.tgz#b3248295276cf8c6f153ebe6a9aba0c988cb2599" integrity sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw== dependencies: "@types/node" "*" "@typescript-eslint/eslint-plugin@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.4.1.tgz#b8acea0373bd2a388ac47df44652f00bf8b368f5" integrity sha512-O+8Utz8pb4OmcA+Nfi5THQnQpHSD2sDUNw9AxNHpuYOo326HZTtG8gsfT+EAYuVrFNaLyNb2QnUNkmTRDskuRA== dependencies: "@typescript-eslint/experimental-utils" "4.4.1" "@typescript-eslint/scope-manager" "4.4.1" debug "^4.1.1" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.4.1.tgz#40613b9757fa0170de3e0043254dbb077cafac0c" integrity sha512-Nt4EVlb1mqExW9cWhpV6pd1a3DkUbX9DeyYsdoeziKOpIJ04S2KMVDO+SEidsXRH/XHDpbzXykKcMTLdTXH6cQ== dependencies: "@types/json-schema" "^7.0.3" "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" eslint-scope "^5.0.0" eslint-utils "^2.0.0" "@typescript-eslint/parser@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.4.1.tgz#25fde9c080611f303f2f33cedb145d2c59915b80" integrity sha512-S0fuX5lDku28Au9REYUsV+hdJpW/rNW0gWlc4SXzF/kdrRaAVX9YCxKpziH7djeWT/HFAjLZcnY7NJD8xTeUEg== dependencies: "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" debug "^4.1.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.4.1.tgz#d19447e60db2ce9c425898d62fa03b2cce8ea3f9" integrity sha512-2oD/ZqD4Gj41UdFeWZxegH3cVEEH/Z6Bhr/XvwTtGv66737XkR4C9IqEkebCuqArqBJQSj4AgNHHiN1okzD/wQ== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.4.1.tgz#c507b35cf523bc7ba00aae5f75ee9b810cdabbc1" integrity sha512-KNDfH2bCyax5db+KKIZT4rfA8rEk5N0EJ8P0T5AJjo5xrV26UAzaiqoJCxeaibqc0c/IvZxp7v2g3difn2Pn3w== "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.4.1.tgz#598f6de488106c2587d47ca2462c60f6e2797cb8" integrity sha512-wP/V7ScKzgSdtcY1a0pZYBoCxrCstLrgRQ2O9MmCUZDtmgxCO/TCqOTGRVwpP4/2hVfqMz/Vw1ZYrG8cVxvN3g== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" debug "^4.1.1" globby "^11.0.1" is-glob "^4.0.1" lodash "^4.17.15" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.4.1.tgz#1769dc7a9e2d7d2cfd3318b77ed8249187aed5c3" integrity sha512-H2JMWhLaJNeaylSnMSQFEhT/S/FsJbebQALmoJxMPMxLtlVAMy2uJP/Z543n9IizhjRayLSqoInehCeNW9rWcw== dependencies: "@typescript-eslint/types" "4.4.1" eslint-visitor-keys "^2.0.0" "@vscode/l10n@^0.0.10": version "0.0.10" resolved "https://registry.yarnpkg.com/@vscode/l10n/-/l10n-0.0.10.tgz#9c513107c690c0dd16e3ec61e453743de15ebdb0" integrity sha512-E1OCmDcDWa0Ya7vtSjp/XfHFGqYJfh+YPC1RkATU71fTac+j1JjCcB3qwSzmlKAighx2WxhLlfhS0RwAN++PFQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" integrity sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw== dependencies: "@webassemblyjs/helper-numbers" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz#f6c61a705f0fd7a6aecaa4e8198f23d9dc179e4f" integrity sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz#1a63192d8788e5c012800ba6a7a46c705288fd16" integrity sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz#832a900eb444884cde9a7cad467f81500f5e5ab5" integrity sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz#64d81da219fbbba1e3bd1bfc74f6e8c4e10a62ae" integrity sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ== dependencies: "@webassemblyjs/floating-point-hex-parser" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz#f328241e41e7b199d0b20c18e88429c4433295e1" integrity sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz#21ee065a7b635f319e738f0dd73bfbda281c097a" integrity sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz#963929e9bbd05709e7e12243a099180812992614" integrity sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ== dependencies: "@xtuc/ieee754" "^1.2.0" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.11.1.tgz#ce814b45574e93d76bae1fb2644ab9cdd9527aa5" integrity sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw== dependencies: "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.11.1.tgz#d1f8b764369e7c6e6bae350e854dec9a59f0a3ff" integrity sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz#ad206ebf4bf95a058ce9880a8c092c5dec8193d6" integrity sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/helper-wasm-section" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-opt" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/wast-printer" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz#86c5ea304849759b7d88c47a32f4f039ae3c8f76" integrity sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz#657b4c2202f4cf3b345f8a4c6461c8c2418985f2" integrity sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz#86ca734534f417e9bd3c67c7a1c75d8be41fb199" integrity sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz#d0c73beda8eec5426f10ae8ef55cee5e7084c2f0" integrity sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg== dependencies: "@webassemblyjs/ast" "1.11.1" "@xtuc/long" "4.2.2" "@webpack-cli/configtest@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== "@webpack-cli/info@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== dependencies: envinfo "^7.7.3" "@webpack-cli/serve@^1.7.0": version "1.7.0" resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== "@xtuc/ieee754@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== "@xtuc/[email protected]": version "4.2.2" resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw== dependencies: mime-types "~2.1.34" negotiator "0.6.3" acorn-import-assertions@^1.7.6: version "1.8.0" resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz#ba2b5939ce62c238db6d93d81c9b111b29b855e9" integrity sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw== acorn-jsx@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.2.0.tgz#4c66069173d6fdd68ed85239fc256226182b2ebe" integrity sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ== acorn@^7.1.1, acorn@^7.2.0: version "7.3.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.3.1.tgz#85010754db53c3fbaf3b9ea3e083aa5c5d147ffd" integrity sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA== acorn@^8.5.0, acorn@^8.7.1: version "8.8.2" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.2.tgz#1b2f25db02af965399b9776b0c2c391276d37c4a" integrity sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw== aggregate-error@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.0.1.tgz#db2fe7246e536f40d9b5442a39e117d7dd6a24e0" integrity sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA== dependencies: clean-stack "^2.0.0" indent-string "^4.0.0" ajv-keywords@^3.4.1: version "3.4.1" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== ajv-keywords@^3.5.2: version "3.5.2" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d" integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.2, ajv@^6.12.5: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== dependencies: fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" json-schema-traverse "^0.4.1" uri-js "^4.2.2" ansi-colors@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: version "4.3.1" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.1.tgz#a5c47cc43181f1f38ffd7076837700d395522a61" integrity sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA== dependencies: type-fest "^0.11.0" ansi-regex@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.1.tgz#164daac87ab2d6f6db3a29875e2d1766582dabed" integrity sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g== ansi-regex@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== ansi-regex@^6.0.0: version "6.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359" integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA== dependencies: "@types/color-name" "^1.1.1" color-convert "^2.0.1" anymatch@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.0.3.tgz#2fb624fe0e84bccab00afee3d0006ed310f22f09" integrity sha512-c6IvoeBECQlMVuYUjSwimnhmztImpErfxJzWZhIQinIvQWoGOnB0dLIgifbPHQt5heS6mNlaZG16f06H3C8t1g== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" integrity sha1-ml9pkFGx5wczKPKgCJaLZOopVdI= array-includes@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.0.3.tgz#184b48f62d92d7452bb31b323165c7f8bd02266d" integrity sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0= dependencies: define-properties "^1.1.2" es-abstract "^1.7.0" array-includes@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.1.tgz#cdd67e6852bdf9c1215460786732255ed2459348" integrity sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0" is-string "^1.0.5" array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= array.prototype.flat@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz#0de82b426b0318dbfdb940089e38b043d37f6c7b" integrity sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" arrify@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= assertion-error@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b" integrity sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw== astral-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg== astral-regex@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== async@^3.2.0: version "3.2.4" resolved "https://registry.yarnpkg.com/async/-/async-3.2.4.tgz#2d22e00f8cddeb5fde5dd33522b56d1cf569a81c" integrity sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ== asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= at-least-node@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== bail@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/bail/-/bail-2.0.1.tgz#d676736373a374058a935aec81b94c12ba815771" integrity sha512-d5FoTAr2S5DSUPKl85WNm2yUwsINN8eidIdIwsOge2t33DaOfOdSmmsI11jMN3GmALCXaw+Y6HMVHDzePshFAA== balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== before-after-hook@^2.2.0: version "2.2.3" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.3.tgz#c51e809c81a4e354084422b9b26bad88249c517c" integrity sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ== big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== binary-extensions@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== [email protected]: version "1.20.1" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.1.tgz#b1812a8912c195cd371a3ee5e66faa2338a5c668" integrity sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw== dependencies: bytes "3.1.2" content-type "~1.0.4" debug "2.6.9" depd "2.0.0" destroy "1.2.0" http-errors "2.0.0" iconv-lite "0.4.24" on-finished "2.4.1" qs "6.11.0" raw-body "2.5.1" type-is "~1.6.18" unpipe "1.0.0" boolean@^3.0.1: version "3.2.0" resolved "https://registry.yarnpkg.com/boolean/-/boolean-3.2.0.tgz#9e5294af4e98314494cbb17979fa54ca159f116b" integrity sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" brace-expansion@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" braces@^3.0.1, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: fill-range "^7.0.1" browserslist@^4.14.5: version "4.21.2" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.2.tgz#59a400757465535954946a400b841ed37e2b4ecf" integrity sha512-MonuOgAtUB46uP5CezYbRaYKBNt2LxP0yX+Pmj4LkcDFGkn9Cbpi83d9sCjwQDErXsIJSzY5oKGDbgOlF/LPAA== dependencies: caniuse-lite "^1.0.30001366" electron-to-chromium "^1.4.188" node-releases "^2.0.6" update-browserslist-db "^1.0.4" btoa-lite@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/btoa-lite/-/btoa-lite-1.0.0.tgz#337766da15801210fdd956c22e9c6891ab9d0337" integrity sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA== buffer-crc32@~0.2.3: version "0.2.13" resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" integrity sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ== [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk= buffer-from@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== buffer-from@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== buffer@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== dependencies: base64-js "^1.3.1" ieee754 "^1.2.1" builtins@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/builtins/-/builtins-4.0.0.tgz#a8345420de82068fdc4d6559d0456403a8fb1905" integrity sha512-qC0E2Dxgou1IHhvJSLwGDSTvokbRovU5zZFuDY6oY8Y2lF3nGt5Ad8YZK7GMtqzY84Wu7pXTPeHQeHcXSXsRhw== dependencies: semver "^7.0.0" [email protected]: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== cacheable-lookup@^5.0.3: version "5.0.4" resolved "https://registry.yarnpkg.com/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz#5a6b865b2c44357be3d5ebc2a467b032719a7005" integrity sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA== cacheable-request@^7.0.2: version "7.0.2" resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-7.0.2.tgz#ea0d0b889364a25854757301ca12b2da77f91d27" integrity sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew== dependencies: clone-response "^1.0.2" get-stream "^5.1.0" http-cache-semantics "^4.0.0" keyv "^4.0.0" lowercase-keys "^2.0.0" normalize-url "^6.0.1" responselike "^2.0.0" call-bind@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== dependencies: function-bind "^1.1.1" get-intrinsic "^1.0.2" callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== camelcase@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== caniuse-lite@^1.0.30001366: version "1.0.30001367" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001367.tgz#2b97fe472e8fa29c78c5970615d7cd2ee414108a" integrity sha512-XDgbeOHfifWV3GEES2B8rtsrADx4Jf+juKX2SICJcaUhjYBO3bR96kvEIHa15VU6ohtOhBZuPGGYGbXMRn0NCw== chai@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/chai/-/chai-4.2.0.tgz#760aa72cf20e3795e84b12877ce0e83737aa29e5" integrity sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw== dependencies: assertion-error "^1.1.0" check-error "^1.0.2" deep-eql "^3.0.1" get-func-name "^2.0.0" pathval "^1.1.0" type-detect "^4.0.5" chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" chalk@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" chalk@^4.0.0, chalk@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" character-entities-legacy@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz#57f4d00974c696e8f74e9f493e7fcb75b44d7ee7" integrity sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA== character-entities@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-2.0.0.tgz#508355fcc8c73893e0909efc1a44d28da2b6fdf3" integrity sha512-oHqMj3eAuJ77/P5PaIRcqk+C3hdfNwyCD2DAUcD5gyXkegAuF2USC40CEqPscDk4I8FRGMTojGJQkXDsN5QlJA== character-reference-invalid@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-2.0.0.tgz#a0bdeb89c051fe7ed5d3158b2f06af06984f2813" integrity sha512-pE3Z15lLRxDzWJy7bBHBopRwfI20sbrMVLQTC7xsPglCHf4Wv1e167OgYAFP78co2XlhojDyAqA+IAJse27//g== chardet@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== check-error@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= check-for-leaks@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/check-for-leaks/-/check-for-leaks-1.2.1.tgz#4ac108ee3f8e6b99f5ad36f6b98cba1d7f4816d0" integrity sha512-9OdOSRZY6N0w5JCdJpqsC5MkD6EPGYpHmhtf4l5nl3DRETDZshP6C1EGN/vVhHDTY6AsOK3NhdFfrMe3NWZl7g== dependencies: anymatch "^3.0.2" minimist "^1.2.0" parse-gitignore "^0.4.0" walk-sync "^0.3.2" chokidar@^3.0.0: version "3.5.2" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== dependencies: anymatch "~3.1.2" braces "~3.0.2" glob-parent "~5.1.2" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" readdirp "~3.6.0" optionalDependencies: fsevents "~2.3.2" chownr@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== chrome-trace-event@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" integrity sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ== dependencies: tslib "^1.9.0" chromium-pickle-js@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz#04a106672c18b085ab774d983dfa3ea138f22205" integrity sha1-BKEGZywYsIWrd02YPfo+oTjyIgU= clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== cli-cursor@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" integrity sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU= dependencies: restore-cursor "^2.0.0" cli-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== dependencies: restore-cursor "^3.1.0" cli-spinners@^2.0.0, cli-spinners@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== [email protected], cli-truncate@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== dependencies: slice-ansi "^3.0.0" string-width "^4.2.0" cli-width@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" integrity sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw== clone-deep@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== dependencies: is-plain-object "^2.0.4" kind-of "^6.0.2" shallow-clone "^3.0.0" clone-response@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.2.tgz#d1dc973920314df67fbeb94223b4ee350239e96b" integrity sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws= dependencies: mimic-response "^1.0.0" clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4= [email protected]: version "3.1.0" resolved "https://registry.yarnpkg.com/co/-/co-3.1.0.tgz#4ea54ea5a08938153185e15210c68d9092bc1b78" integrity sha1-TqVOpaCJOBUxheFSEMaNkJK8G3g= color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-convert@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== dependencies: color-name "~1.1.4" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= color-name@~1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== colorette@^2.0.14: version "2.0.19" resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== [email protected]: version "1.4.0" resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== colors@^1.1.2: version "1.3.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.3.tgz#39e005d546afe01e01f9c4ca8fa50f686a01205d" integrity sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg== combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== dependencies: delayed-stream "~1.0.0" commander@^2.20.0, commander@^2.9.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== commander@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== commander@^5.0.0, commander@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== commander@^7.0.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== commander@~9.4.1: version "9.4.1" resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.1.tgz#d1dd8f2ce6faf93147295c0df13c7c21141cfbdd" integrity sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw== compress-brotli@^1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/compress-brotli/-/compress-brotli-1.3.8.tgz#0c0a60c97a989145314ec381e84e26682e7b38db" integrity sha512-lVcQsjhxhIXsuupfy9fmZUFtAIdBmXA7EGY6GBdgZ++qkM9zG4YFT8iU7FoBxzryNDMOpD1HIFHUSX4D87oqhQ== dependencies: "@types/json-buffer" "~3.0.0" json-buffer "~3.0.1" [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== concat-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-2.0.0.tgz#414cf5af790a48c60ab9be4527d56d5e41133cb1" integrity sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A== dependencies: buffer-from "^1.0.0" inherits "^2.0.3" readable-stream "^3.0.2" typedarray "^0.0.6" contains-path@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo= [email protected]: version "0.5.4" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== dependencies: safe-buffer "5.2.1" content-type@~1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA== [email protected]: version "1.0.6" resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw= [email protected]: version "0.5.0" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b" integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw== core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= cosmiconfig@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982" integrity sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg== dependencies: "@types/parse-json" "^4.0.0" import-fresh "^3.1.0" parse-json "^5.0.0" path-type "^4.0.0" yaml "^1.7.2" cross-spawn@^6.0.5: version "6.0.5" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== dependencies: nice-try "^1.0.4" path-key "^2.0.1" semver "^5.5.0" shebang-command "^1.2.0" which "^1.2.9" cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== dependencies: path-key "^3.1.0" shebang-command "^2.0.0" which "^2.0.1" debug-log@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f" integrity sha1-IwdjLUwEOCuN+KMvcLiVBG1SdF8= [email protected], debug@^2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" debug@^3.1.0: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" debug@^4.0.0: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== dependencies: ms "2.1.2" debug@^4.0.1, debug@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== dependencies: ms "^2.1.1" debug@^4.1.0, debug@^4.3.3, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" decode-named-character-reference@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz#daabac9690874c394c81e4162a0304b35d824f0e" integrity sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg== dependencies: character-entities "^2.0.0" decompress-response@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== dependencies: mimic-response "^3.1.0" dedent@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw= deep-eql@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df" integrity sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw== dependencies: type-detect "^4.0.0" deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== deep-is@^0.1.3, deep-is@~0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= defaults@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.3.tgz#c656051e9817d9ff08ed881477f3fe4019f3ef7d" integrity sha1-xlYFHpgX2f8I7YgUd/P+QBnz730= dependencies: clone "^1.0.2" defer-to-connect@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587" integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg== define-properties@^1.1.2, define-properties@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" deglob@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/deglob/-/deglob-4.0.1.tgz#0685c6383992fd6009be10653a2b1116696fad55" integrity sha512-/g+RDZ7yf2HvoW+E5Cy+K94YhgcFgr6C8LuHZD1O5HoNPkf3KY6RfXJ0DBGlB/NkLi5gml+G9zqRzk9S0mHZCg== dependencies: find-root "^1.0.0" glob "^7.0.5" ignore "^5.0.0" pkg-config "^1.1.0" run-parallel "^1.1.2" uniq "^1.0.1" delayed-stream@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== dequal@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== detect-node@^2.0.4: version "2.1.0" resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== diff@^3.1.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== diff@^5.0.0: version "5.1.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.1.0.tgz#bc52d298c5ea8df9194800224445ed43ffc87e40" integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== dependencies: path-type "^4.0.0" [email protected]: version "1.5.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" integrity sha1-N53Ocw9hZvds76TmcHoVmwLFpvo= dependencies: esutils "^2.0.2" isarray "^1.0.0" doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" integrity sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw== dependencies: esutils "^2.0.2" doctrine@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== dependencies: esutils "^2.0.2" dotenv-safe@^4.0.4: version "4.0.4" resolved "https://registry.yarnpkg.com/dotenv-safe/-/dotenv-safe-4.0.4.tgz#8b0e7ced8e70b1d3c5d874ef9420e406f39425b3" integrity sha1-iw587Y5wsdPF2HTvlCDkBvOUJbM= dependencies: dotenv "^4.0.0" dotenv@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-4.0.0.tgz#864ef1379aced55ce6f95debecdce179f7a0cd1d" integrity sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0= dugite@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/dugite/-/dugite-2.3.0.tgz#ff6fdb4c899f84ed6695c9e01eaf4364a6211f13" integrity sha512-78zuD3p5lx2IS8DilVvHbXQXRo+hGIb3EAshTEC3ZyBLyArKegA8R/6c4Ne1aUlx6JRf3wmKNgYkdJOYMyj9aA== dependencies: progress "^2.0.3" tar "^6.1.11" duplexer@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= [email protected]: version "1.0.11" resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf" integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ== dependencies: safe-buffer "^5.0.1" [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.188: version "1.4.195" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.195.tgz#139b2d95a42a3f17df217589723a1deac71d1473" integrity sha512-vefjEh0sk871xNmR5whJf9TEngX+KTKS3hOHpjoMpauKkwlGwtMz1H8IaIjAT/GNnX0TbGwAdmVoXCAzXf+PPg== emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== emoji-regex@^9.2.2: version "9.2.2" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" integrity sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q== encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= end-of-stream@^1.1.0: version "1.4.4" resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" enhanced-resolve@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" integrity sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng== dependencies: graceful-fs "^4.1.2" memory-fs "^0.4.0" tapable "^1.0.0" enhanced-resolve@^5.10.0: version "5.12.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz#300e1c90228f5b570c4d35babf263f6da7155634" integrity sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ== dependencies: graceful-fs "^4.2.4" tapable "^2.2.0" enquirer@^2.3.5: version "2.3.6" resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== dependencies: ansi-colors "^4.1.1" ensure-posix-path@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/ensure-posix-path/-/ensure-posix-path-1.1.1.tgz#3c62bdb19fa4681544289edb2b382adc029179ce" integrity sha512-VWU0/zXzVbeJNXvME/5EmLuEj2TauvoaTz6aFYK1Z92JCBlDlZ3Gu0tuGR42kpW1754ywTs+QB0g5TP0oj9Zaw== entities@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== entities@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== env-paths@^2.2.0, env-paths@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== envinfo@^7.7.3: version "7.8.1" resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== errno@^0.1.3: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== dependencies: prr "~1.0.1" error-ex@^1.2.0, error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" es-abstract@^1.17.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.5: version "1.17.6" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" is-callable "^1.2.0" is-regex "^1.1.0" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" string.prototype.trimend "^1.0.1" string.prototype.trimstart "^1.0.1" es-abstract@^1.7.0: version "1.13.0" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9" integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg== dependencies: es-to-primitive "^1.2.0" function-bind "^1.1.1" has "^1.0.3" is-callable "^1.1.4" is-regex "^1.0.4" object-keys "^1.0.12" es-module-lexer@^0.9.0: version "0.9.3" resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== es-to-primitive@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es-to-primitive@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es6-error@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/es6-error/-/es6-error-4.1.1.tgz#9e3af407459deed47e9a91f9b885a84eb05c561d" integrity sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg== es6-object-assign@^1.0.3: version "1.1.0" resolved "https://registry.yarnpkg.com/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= escape-string-regexp@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== [email protected]: version "8.1.0" resolved "https://registry.yarnpkg.com/eslint-config-standard-jsx/-/eslint-config-standard-jsx-8.1.0.tgz#314c62a0e6f51f75547f89aade059bec140edfc7" integrity sha512-ULVC8qH8qCqbU792ZOO6DaiaZyHNS/5CZt3hKqHkEhVlhPEPN3nfBqqxJCyp59XrjIBZPu1chMYe9T2DXZ7TMw== [email protected], eslint-config-standard@^14.1.1: version "14.1.1" resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-14.1.1.tgz#830a8e44e7aef7de67464979ad06b406026c56ea" integrity sha512-Z9B+VR+JIXRxz21udPTL9HpFMyoMUEeX1G251EQ6e05WD9aPVtVBn09XUmZ259wCMlCDmYDSZG62Hhm+ZTJcUg== eslint-import-resolver-node@^0.3.2, eslint-import-resolver-node@^0.3.3: version "0.3.4" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz#85ffa81942c25012d8231096ddf679c03042c717" integrity sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA== dependencies: debug "^2.6.9" resolve "^1.13.1" eslint-module-utils@^2.4.0, eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" integrity sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA== dependencies: debug "^2.6.9" pkg-dir "^2.0.0" eslint-plugin-es@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-2.0.0.tgz#0f5f5da5f18aa21989feebe8a73eadefb3432976" integrity sha512-f6fceVtg27BR02EYnBhgWLFQfK6bN4Ll0nQFrBHOlCsAyxeZkn0NHns5O0YZOPrV1B3ramd6cgFwaoFLcSkwEQ== dependencies: eslint-utils "^1.4.2" regexpp "^3.0.0" eslint-plugin-es@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz#75a7cdfdccddc0589934aeeb384175f221c57893" integrity sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ== dependencies: eslint-utils "^2.0.0" regexpp "^3.0.0" eslint-plugin-import@^2.22.0: version "2.22.0" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz#92f7736fe1fde3e2de77623c838dd992ff5ffb7e" integrity sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg== dependencies: array-includes "^3.1.1" array.prototype.flat "^1.2.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.3" eslint-module-utils "^2.6.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.1" read-pkg-up "^2.0.0" resolve "^1.17.0" tsconfig-paths "^3.9.0" eslint-plugin-import@~2.18.0: version "2.18.2" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.18.2.tgz#02f1180b90b077b33d447a17a2326ceb400aceb6" integrity sha512-5ohpsHAiUBRNaBWAF08izwUGlbrJoJJ+W9/TBwsGoR1MnlgfwMIKrFeSjWbt6moabiXW9xNvtFz+97KHRfI4HQ== dependencies: array-includes "^3.0.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.2" eslint-module-utils "^2.4.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.0" read-pkg-up "^2.0.0" resolve "^1.11.0" eslint-plugin-mocha@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-mocha/-/eslint-plugin-mocha-7.0.1.tgz#b2e9e8ebef7836f999a83f8bab25d0e0c05f0d28" integrity sha512-zkQRW9UigRaayGm/pK9TD5RjccKXSgQksNtpsXbG9b6L5I+jNx7m98VUbZ4w1H1ArlNA+K7IOH+z8TscN6sOYg== dependencies: eslint-utils "^2.0.0" ramda "^0.27.0" eslint-plugin-node@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" integrity sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g== dependencies: eslint-plugin-es "^3.0.0" eslint-utils "^2.0.0" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-node@~10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-10.0.0.tgz#fd1adbc7a300cf7eb6ac55cf4b0b6fc6e577f5a6" integrity sha512-1CSyM/QCjs6PXaT18+zuAXsjXGIGo5Rw630rSKwokSs2jrYURQc4R5JZpoanNCqwNmepg+0eZ9L7YiRUJb8jiQ== dependencies: eslint-plugin-es "^2.0.0" eslint-utils "^1.4.2" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-promise@~4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz#845fd8b2260ad8f82564c1222fce44ad71d9418a" integrity sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw== eslint-plugin-react@~7.14.2: version "7.14.3" resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz#911030dd7e98ba49e1b2208599571846a66bdf13" integrity sha512-EzdyyBWC4Uz2hPYBiEJrKCUi2Fn+BJ9B/pJQcjw5X+x/H2Nm59S4MJIvL4O5NEE0+WbnQwEBxWY03oUk+Bc3FA== dependencies: array-includes "^3.0.3" doctrine "^2.1.0" has "^1.0.3" jsx-ast-utils "^2.1.0" object.entries "^1.1.0" object.fromentries "^2.0.0" object.values "^1.1.0" prop-types "^15.7.2" resolve "^1.10.1" eslint-plugin-standard@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.1.tgz#ff0519f7ffaff114f76d1bd7c3996eef0f6e20b4" integrity sha512-v/KBnfyaOMPmZc/dmc6ozOdWqekGp7bBGq4jLAecEfPGmfKiWS4sA8sC0LqiV9w5qmXAtXVn4M3p1jSyhY85SQ== eslint-plugin-standard@~4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.0.tgz#f845b45109c99cd90e77796940a344546c8f6b5c" integrity sha512-OwxJkR6TQiYMmt1EsNRMe5qG3GsbjlcOhbGUBY4LtavF9DsLaTcoR+j2Tdjqi23oUwKNUqX7qcn5fPStafMdlA== eslint-plugin-typescript@^0.14.0: version "0.14.0" resolved "https://registry.yarnpkg.com/eslint-plugin-typescript/-/eslint-plugin-typescript-0.14.0.tgz#068549c3f4c7f3f85d88d398c29fa96bf500884c" integrity sha512-2u1WnnDF2mkWWgU1lFQ2RjypUlmRoBEvQN02y9u+IL12mjWlkKFGEBnVsjs9Y8190bfPQCvWly1c2rYYUSOxWw== dependencies: requireindex "~1.1.0" [email protected], eslint-scope@^5.0.0, eslint-scope@^5.1.0: version "5.1.1" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== dependencies: esrecurse "^4.3.0" estraverse "^4.1.1" eslint-utils@^1.4.2, eslint-utils@^1.4.3: version "1.4.3" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f" integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q== dependencies: eslint-visitor-keys "^1.1.0" eslint-utils@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" eslint-visitor-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2" integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A== eslint-visitor-keys@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== eslint-visitor-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8" integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== eslint@^7.4.0: version "7.4.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.4.0.tgz#4e35a2697e6c1972f9d6ef2b690ad319f80f206f" integrity sha512-gU+lxhlPHu45H3JkEGgYhWhkR9wLHHEXC9FbWFnTlEkbKyZKWgWRLgf61E8zWmBuI6g5xKBph9ltg3NtZMVF8g== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^4.0.0" cross-spawn "^7.0.2" debug "^4.0.1" doctrine "^3.0.0" enquirer "^2.3.5" eslint-scope "^5.1.0" eslint-utils "^2.0.0" eslint-visitor-keys "^1.2.0" espree "^7.1.0" esquery "^1.2.0" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash "^4.17.14" minimatch "^3.0.4" natural-compare "^1.4.0" optionator "^0.9.1" progress "^2.0.0" regexpp "^3.1.0" semver "^7.2.1" strip-ansi "^6.0.0" strip-json-comments "^3.1.0" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" eslint@~6.8.0: version "6.8.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-6.8.0.tgz#62262d6729739f9275723824302fb227c8c93ffb" integrity sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^2.1.0" cross-spawn "^6.0.5" debug "^4.0.1" doctrine "^3.0.0" eslint-scope "^5.0.0" eslint-utils "^1.4.3" eslint-visitor-keys "^1.1.0" espree "^6.1.2" esquery "^1.0.1" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" inquirer "^7.0.0" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.3.0" lodash "^4.17.14" minimatch "^3.0.4" mkdirp "^0.5.1" natural-compare "^1.4.0" optionator "^0.8.3" progress "^2.0.0" regexpp "^2.0.1" semver "^6.1.2" strip-ansi "^5.2.0" strip-json-comments "^3.0.1" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" espree@^6.1.2: version "6.2.1" resolved "https://registry.yarnpkg.com/espree/-/espree-6.2.1.tgz#77fc72e1fd744a2052c20f38a5b575832e82734a" integrity sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw== dependencies: acorn "^7.1.1" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.1.0" espree@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/espree/-/espree-7.1.0.tgz#a9c7f18a752056735bf1ba14cb1b70adc3a5ce1c" integrity sha512-dcorZSyfmm4WTuTnE5Y7MEN1DyoPYy1ZR783QW1FJoenn7RailyWFsq/UL6ZAAA7uXurN9FIpYyUs3OfiIW+Qw== dependencies: acorn "^7.2.0" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.2.0" esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== esquery@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" integrity sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA== dependencies: estraverse "^4.0.0" esquery@^1.2.0: version "1.3.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.3.1.tgz#b78b5828aa8e214e29fb74c4d5b752e1c033da57" integrity sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ== dependencies: estraverse "^5.1.0" esrecurse@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== dependencies: estraverse "^5.2.0" estraverse@^4.0.0, estraverse@^4.1.1: version "4.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== estraverse@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.1.0.tgz#374309d39fd935ae500e7b92e8a6b4c720e59642" integrity sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw== estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== esutils@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== etag@~1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc= events-to-array@^1.0.1: version "1.1.2" resolved "https://registry.yarnpkg.com/events-to-array/-/events-to-array-1.1.2.tgz#2d41f563e1fe400ed4962fe1a4d5c6a7539df7f6" integrity sha1-LUH1Y+H+QA7Uli/hpNXGp1Od9/Y= events@^3.0.0, events@^3.2.0: version "3.3.0" resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== execa@^4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2" integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A== dependencies: cross-spawn "^7.0.0" get-stream "^5.0.0" human-signals "^1.1.1" is-stream "^2.0.0" merge-stream "^2.0.0" npm-run-path "^4.0.0" onetime "^5.1.0" signal-exit "^3.0.2" strip-final-newline "^2.0.0" express@^4.16.4: version "4.18.2" resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59" integrity sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ== dependencies: accepts "~1.3.8" array-flatten "1.1.1" body-parser "1.20.1" content-disposition "0.5.4" content-type "~1.0.4" cookie "0.5.0" cookie-signature "1.0.6" debug "2.6.9" depd "2.0.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" finalhandler "1.2.0" fresh "0.5.2" http-errors "2.0.0" merge-descriptors "1.0.1" methods "~1.1.2" on-finished "2.4.1" parseurl "~1.3.3" path-to-regexp "0.1.7" proxy-addr "~2.0.7" qs "6.11.0" range-parser "~1.2.1" safe-buffer "5.2.1" send "0.18.0" serve-static "1.15.0" setprototypeof "1.2.0" statuses "2.0.1" type-is "~1.6.18" utils-merge "1.0.1" vary "~1.1.2" extend@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== external-editor@^3.0.3: version "3.1.0" resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== dependencies: chardet "^0.7.0" iconv-lite "^0.4.24" tmp "^0.0.33" extract-zip@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-2.0.1.tgz#663dca56fe46df890d5f131ef4a06d22bb8ba13a" integrity sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg== dependencies: debug "^4.1.1" get-stream "^5.1.0" yauzl "^2.10.0" optionalDependencies: "@types/yauzl" "^2.9.1" fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-glob@^3.1.1: version "3.2.4" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3" integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ== dependencies: "@nodelib/fs.stat" "^2.0.2" "@nodelib/fs.walk" "^1.2.3" glob-parent "^5.1.0" merge2 "^1.3.0" micromatch "^4.0.2" picomatch "^2.2.1" fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= fastest-levenshtein@^1.0.12: version "1.0.14" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.14.tgz#9054384e4b7a78c88d01a4432dc18871af0ac859" integrity sha512-tFfWHjnuUfKE186Tfgr+jtaFc0mZTApEgKDOeyN+FwOqRkO/zK/3h1AiRd8u8CY53owL3CUmGr/oI9p/RdyLTA== fastq@^1.6.0: version "1.8.0" resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481" integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q== dependencies: reusify "^1.0.4" fault@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fault/-/fault-2.0.0.tgz#ad2198a6e28e344dcda76a7b32406b1039f0b707" integrity sha512-JsDj9LFcoC+4ChII1QpXPA7YIaY8zmqPYw7h9j5n7St7a0BBKfNnwEBAUQRBx70o2q4rs+BeSNHk8Exm6xE7fQ== dependencies: format "^0.2.0" fd-slicer@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" integrity sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g== dependencies: pend "~1.2.0" figgy-pudding@^3.5.1: version "3.5.2" resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e" integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw== figures@^3.0.0, figures@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/figures/-/figures-3.2.0.tgz#625c18bd293c604dc4a8ddb2febf0c88341746af" integrity sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg== dependencies: escape-string-regexp "^1.0.5" file-entry-cache@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-5.0.1.tgz#ca0f6efa6dd3d561333fb14515065c2fafdf439c" integrity sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g== dependencies: flat-cache "^2.0.1" fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== dependencies: to-regex-range "^5.0.1" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32" integrity sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg== dependencies: debug "2.6.9" encodeurl "~1.0.2" escape-html "~1.0.3" on-finished "2.4.1" parseurl "~1.3.3" statuses "2.0.1" unpipe "~1.0.0" find-root@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng== find-up@^2.0.0, find-up@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= dependencies: locate-path "^2.0.0" find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" find-up@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== dependencies: locate-path "^5.0.0" path-exists "^4.0.0" flat-cache@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0" integrity sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA== dependencies: flatted "^2.0.0" rimraf "2.6.3" write "1.0.3" flatted@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== folder-hash@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/folder-hash/-/folder-hash-2.1.2.tgz#7109f9cd0cbca271936d1b5544b156d6571e6cfd" integrity sha512-PmMwEZyNN96EMshf7sek4OIB7ADNsHOJ7VIw7pO0PBI0BNfEsi7U8U56TBjjqqwQ0WuBv8se0HEfmbw5b/Rk+w== dependencies: debug "^3.1.0" graceful-fs "~4.1.11" minimatch "~3.0.4" form-data@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" form-data@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" format@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" integrity sha1-1hcBB+nv3E7TDJ3DkBbflCtctYs= [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow== [email protected]: version "0.5.2" resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac= fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" integrity sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ== dependencies: graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^2.0.0" fs-extra@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9" integrity sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw== dependencies: graceful-fs "^4.1.2" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== dependencies: graceful-fs "^4.2.0" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^9.0.1: version "9.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc" integrity sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ== dependencies: at-least-node "^1.0.0" graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^1.0.0" fs-minipass@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== dependencies: minipass "^3.0.0" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== functional-red-black-tree@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= get-func-name@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41" integrity sha1-6td0q+5y4gQJQzoGY2YCPdaIekE= get-intrinsic@^1.0.2: version "1.2.0" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.0.tgz#7ad1dc0535f3a2904bba075772763e5051f6d05f" integrity sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q== dependencies: function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.3" get-own-enumerable-property-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203" integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg== get-stdin@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-7.0.0.tgz#8d5de98f15171a125c5e516643c7a6d0ea8a96f6" integrity sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ== get-stdin@~9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-9.0.0.tgz#3983ff82e03d56f1b2ea0d3e60325f39d703a575" integrity sha512-dVKBjfWisLAicarI2Sf+JuBE/DghV4UzNAVe9yhEJuzeREd3JhOTE9cUaJTeSa77fsbQUK3pcOpJfM59+VKZaA== get-stream@^5.0.0, get-stream@^5.1.0: version "5.2.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: pump "^3.0.0" getos@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/getos/-/getos-3.2.1.tgz#0134d1f4e00eb46144c5a9c0ac4dc087cbb27dc5" integrity sha512-U56CfOK17OKgTVqozZjUKNdkfEv6jk5WISBJ8SHoagjE6L69zOwl3Z+O8myjY9MEW3i2HPWQBt/LTbCgcC973Q== dependencies: async "^3.2.0" glob-parent@^5.0.0, glob-parent@^5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" glob-to-regexp@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== glob@^7.0.0, glob@^7.0.5, glob@^7.1.3, glob@^7.1.6: version "7.2.0" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" glob@~8.0.3: version "8.0.3" resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" integrity sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^5.0.1" once "^1.3.0" global-agent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/global-agent/-/global-agent-3.0.0.tgz#ae7cd31bd3583b93c5a16437a1afe27cc33a1ab6" integrity sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q== dependencies: boolean "^3.0.1" es6-error "^4.1.1" matcher "^3.0.0" roarr "^2.15.3" semver "^7.3.2" serialize-error "^7.0.1" globals@^12.1.0: version "12.4.0" resolved "https://registry.yarnpkg.com/globals/-/globals-12.4.0.tgz#a18813576a41b00a24a97e7f815918c2e19925f8" integrity sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg== dependencies: type-fest "^0.8.1" globalthis@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.3.tgz#5852882a52b80dc301b0660273e1ed082f0b6ccf" integrity sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA== dependencies: define-properties "^1.1.3" globby@^11.0.0, globby@^11.0.1: version "11.0.1" resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357" integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ== dependencies: array-union "^2.1.0" dir-glob "^3.0.1" fast-glob "^3.1.1" ignore "^5.1.4" merge2 "^1.3.0" slash "^3.0.0" got@^11.8.5: version "11.8.5" resolved "https://registry.yarnpkg.com/got/-/got-11.8.5.tgz#ce77d045136de56e8f024bebb82ea349bc730046" integrity sha512-o0Je4NvQObAuZPHLFoRSkdG2lTgtcynqymzg2Vupdx6PorhaT5MCbIyXG6d4D94kk8ZG57QeosgdiqfJWhEhlQ== dependencies: "@sindresorhus/is" "^4.0.0" "@szmarczak/http-timer" "^4.0.5" "@types/cacheable-request" "^6.0.1" "@types/responselike" "^1.0.0" cacheable-lookup "^5.0.3" cacheable-request "^7.0.2" decompress-response "^6.0.0" http2-wrapper "^1.0.0-beta.5.2" lowercase-keys "^2.0.0" p-cancelable "^2.0.0" responselike "^2.0.0" graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0, graceful-fs@^4.2.4, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== graceful-fs@~4.1.11: version "4.1.15" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA== has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== has-flag@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-5.0.1.tgz#5483db2ae02a472d1d0691462fc587d1843cd940" integrity sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA== has-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= has-symbols@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== has-symbols@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== dependencies: function-bind "^1.1.1" hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw== http-cache-semantics@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3" integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ== dependencies: depd "2.0.0" inherits "2.0.4" setprototypeof "1.2.0" statuses "2.0.1" toidentifier "1.0.1" http2-wrapper@^1.0.0-beta.5.2: version "1.0.3" resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-1.0.3.tgz#b8f55e0c1f25d4ebd08b3b0c2c079f9590800b3d" integrity sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg== dependencies: quick-lru "^5.1.1" resolve-alpn "^1.0.0" human-signals@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== husky@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.1.tgz#511cb3e57de3e3190514ae49ed50f6bc3f50b3e9" integrity sha512-xs7/chUH/CKdOCs7Zy0Aev9e/dKOMZf3K1Az1nar3tzlv0jfqnYtu235bstsWTmXOR0EfINrPa97yy4Lz6RiKw== [email protected], iconv-lite@^0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== ignore@^4.0.6: version "4.0.6" resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.0.0, ignore@^5.1.1, ignore@^5.1.4: version "5.1.8" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== ignore@~5.2.4: version "5.2.4" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== import-fresh@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.1.0.tgz#6d33fa1dcef6df930fae003446f33415af905118" integrity sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-fresh@^3.1.0: version "3.2.1" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66" integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-local@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg== dependencies: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" import-meta-resolve@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-1.1.1.tgz#244fd542fd1fae73550d4f8b3cde3bba1d7b2b18" integrity sha512-JiTuIvVyPaUg11eTrNDx5bgQ/yMKMZffc7YSjvQeSMXy58DO2SQ8BtAf3xteZvmzvjYh14wnqNjL8XVeDy2o9A== dependencies: builtins "^4.0.0" imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= indent-string@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2, [email protected], inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@^1.3.5: version "1.3.7" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.7.tgz#a09363e1911972ea16d7a8851005d84cf09a9a84" integrity sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ== ini@~3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/ini/-/ini-3.0.1.tgz#c76ec81007875bc44d544ff7a11a55d12294102d" integrity sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ== inquirer@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.3.0.tgz#aa3e7cb0c18a410c3c16cdd2bc9dcbe83c4d333e" integrity sha512-K+LZp6L/6eE5swqIcVXrxl21aGDU4S50gKH0/d96OMQnSBCyGyZl/oZhbkVmdp5sBoINHd4xZvFSARh2dk6DWA== dependencies: ansi-escapes "^4.2.1" chalk "^4.1.0" cli-cursor "^3.1.0" cli-width "^3.0.0" external-editor "^3.0.3" figures "^3.0.0" lodash "^4.17.15" mute-stream "0.0.8" run-async "^2.4.0" rxjs "^6.6.0" string-width "^4.1.0" strip-ansi "^6.0.0" through "^2.3.6" interpret@^1.0.0: version "1.4.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== interpret@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== [email protected]: version "1.9.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== is-alphabetical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-2.0.0.tgz#ef6e2caea57c63450fffc7abb6cbdafc5eb96e96" integrity sha512-5OV8Toyq3oh4eq6sbWTYzlGdnMT/DPI5I0zxUBxjiigQsZycpkKF3kskkao3JyYGuYDHvhgJF+DrjMQp9SX86w== is-alphanumerical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-2.0.0.tgz#0fbfeb6a72d21d91143b3d182bf6cf5909ee66f6" integrity sha512-t+2GlJ+hO9yagJ+jU3+HSh80VKvz/3cG2cxbGGm4S0hjKuhWQXgPVUVOZz3tqZzMjhmphZ+1TIJTlRZRoe6GCQ== dependencies: is-alphabetical "^2.0.0" is-decimal "^2.0.0" is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== dependencies: binary-extensions "^2.0.0" is-buffer@^2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== is-callable@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== is-callable@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.0.tgz#83336560b54a38e35e3a2df7afd0454d691468bb" integrity sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw== is-core-module@^2.8.0: version "2.8.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.1.tgz#f59fdfca701d5879d0a6b100a40aa1560ce27211" integrity sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA== dependencies: has "^1.0.3" is-core-module@^2.9.0: version "2.9.0" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== dependencies: has "^1.0.3" is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= is-decimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.0.tgz#db1140337809fd043a056ae40a9bd1cdc563034c" integrity sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw== is-empty@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" integrity sha1-3pu1snhzigWgsJpX4ftNSjQan2s= is-extglob@^2.1.0, is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== is-fullwidth-code-point@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== is-glob@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= dependencies: is-extglob "^2.1.0" is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-hexadecimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.0.tgz#8e1ec9f48fe3eabd90161109856a23e0907a65d5" integrity sha512-vGOtYkiaxwIiR0+Ng/zNId+ZZehGfINwTzdrDqc6iubbnQWhnPuYymOzOKUDqa2cSl59yHnEh2h6MvRLQsyNug== is-interactive@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== is-obj@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= is-plain-obj@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.0.0.tgz#06c0999fd7574edf5a906ba5644ad0feb3a84d22" integrity sha512-NXRbBtUdBioI73y/HmOhogw/U5msYPC9DAtGkJXeFcFWSFZw0mCUsPxk/snTuJHzNKA8kLBK4rH97RMB1BfCXw== is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-plain-object@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-4.1.1.tgz#1a14d6452cbd50790edc7fdaa0aed5a40a35ebb5" integrity sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA== is-plain-object@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== is-regex@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= dependencies: has "^1.0.1" is-regex@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.0.tgz#ece38e389e490df0dc21caea2bd596f987f767ff" integrity sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw== dependencies: has-symbols "^1.0.1" is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= is-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== is-string@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== is-symbol@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== dependencies: has-symbols "^1.0.0" isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= jest-worker@^27.4.5: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== dependencies: "@types/node" "*" merge-stream "^2.0.0" supports-color "^8.0.0" "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^3.13.1, js-yaml@^3.2.7: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== dependencies: argparse "^1.0.7" esprima "^4.0.0" js-yaml@^4.0.0, js-yaml@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== dependencies: argparse "^2.0.1" [email protected], json-buffer@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== json-parse-even-better-errors@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= json-stringify-safe@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== json5@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA== dependencies: minimist "^1.2.0" json5@^2.0.0, json5@^2.1.2: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== jsonc-parser@~3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= optionalDependencies: graceful-fs "^4.1.6" jsonfile@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.0.1.tgz#98966cba214378c8c84b82e085907b40bf614179" integrity sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg== dependencies: universalify "^1.0.0" optionalDependencies: graceful-fs "^4.1.6" jsonwebtoken@^9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz#d0faf9ba1cc3a56255fe49c0961a67e520c1926d" integrity sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw== dependencies: jws "^3.2.2" lodash "^4.17.21" ms "^2.1.1" semver "^7.3.8" jsx-ast-utils@^2.1.0: version "2.4.1" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz#1114a4c1209481db06c690c2b4f488cc665f657e" integrity sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w== dependencies: array-includes "^3.1.1" object.assign "^4.1.0" jwa@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a" integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA== dependencies: buffer-equal-constant-time "1.0.1" ecdsa-sig-formatter "1.0.11" safe-buffer "^5.0.1" jws@^3.2.2: version "3.2.2" resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304" integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA== dependencies: jwa "^1.4.1" safe-buffer "^5.0.1" keyv@^4.0.0: version "4.3.1" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.3.1.tgz#7970672f137d987945821b1a07b524ce5a4edd27" integrity sha512-nwP7AQOxFzELXsNq3zCx/oh81zu4DHWwCE6W9RaeHb7OHO0JpmKS8n801ovVQC7PTsZDWtPA5j1QY+/WWtARYg== dependencies: compress-brotli "^1.3.8" json-buffer "3.0.1" kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== klaw@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" integrity sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g== dependencies: graceful-fs "^4.1.9" kleur@^4.0.3: version "4.1.5" resolved "https://registry.yarnpkg.com/kleur/-/kleur-4.1.5.tgz#95106101795f7050c6c650f350c683febddb1780" integrity sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ== levn@^0.3.0, levn@~0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= dependencies: prelude-ls "~1.1.2" type-check "~0.3.2" levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== dependencies: prelude-ls "^1.2.1" type-check "~0.4.0" libnpmconfig@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/libnpmconfig/-/libnpmconfig-1.2.1.tgz#c0c2f793a74e67d4825e5039e7a02a0044dfcbc0" integrity sha512-9esX8rTQAHqarx6qeZqmGQKBNZR5OIbl/Ayr0qQDy3oXja2iFVQQI81R6GZ2a02bSNZ9p3YOGX1O6HHCb1X7kA== dependencies: figgy-pudding "^3.5.1" find-up "^3.0.0" ini "^1.3.5" lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= linkify-it@^3.0.1: version "3.0.3" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e" integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ== dependencies: uc.micro "^1.0.1" linkify-it@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-4.0.1.tgz#01f1d5e508190d06669982ba31a7d9f56a5751ec" integrity sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw== dependencies: uc.micro "^1.0.1" lint-staged@^10.2.11: version "10.2.11" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-10.2.11.tgz#713c80877f2dc8b609b05bc59020234e766c9720" integrity sha512-LRRrSogzbixYaZItE2APaS4l2eJMjjf5MbclRZpLJtcQJShcvUzKXsNeZgsLIZ0H0+fg2tL4B59fU9wHIHtFIA== dependencies: chalk "^4.0.0" cli-truncate "2.1.0" commander "^5.1.0" cosmiconfig "^6.0.0" debug "^4.1.1" dedent "^0.7.0" enquirer "^2.3.5" execa "^4.0.1" listr2 "^2.1.0" log-symbols "^4.0.0" micromatch "^4.0.2" normalize-path "^3.0.0" please-upgrade-node "^3.2.0" string-argv "0.3.1" stringify-object "^3.3.0" lint@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/lint/-/lint-1.1.2.tgz#35ed064f322547c331358d899868664968ba371f" integrity sha1-Ne0GTzIlR8MxNY2JmGhmSWi6Nx8= listr2@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/listr2/-/listr2-2.2.0.tgz#cb88631258abc578c7fb64e590fe5742f28e4aac" integrity sha512-Q8qbd7rgmEwDo1nSyHaWQeztfGsdL6rb4uh7BA+Q80AZiDET5rVntiU1+13mu2ZTDVaBVbvAD1Db11rnu3l9sg== dependencies: chalk "^4.0.0" cli-truncate "^2.1.0" figures "^3.2.0" indent-string "^4.0.0" log-update "^4.0.0" p-map "^4.0.0" rxjs "^6.5.5" through "^2.3.8" load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-2.0.0.tgz#7947e42149af80d696cbf797bcaabcfe1fe29ca8" integrity sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg= dependencies: graceful-fs "^4.1.2" parse-json "^2.2.0" pify "^2.0.0" strip-bom "^3.0.0" load-json-file@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-5.3.0.tgz#4d3c1e01fa1c03ea78a60ac7af932c9ce53403f3" integrity sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw== dependencies: graceful-fs "^4.1.15" parse-json "^4.0.0" pify "^4.0.1" strip-bom "^3.0.0" type-fest "^0.3.0" load-plugin@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/load-plugin/-/load-plugin-4.0.1.tgz#9a239b0337064c9b8aac82b0c9f89b067db487c5" integrity sha512-4kMi+mOSn/TR51pDo4tgxROHfBHXsrcyEYSGHcJ1o6TtRaP2PsRM5EwmYbj1uiLDvbfA/ohwuSWZJzqGiai8Dw== dependencies: import-meta-resolve "^1.0.0" libnpmconfig "^1.0.0" loader-runner@^4.2.0: version "4.3.0" resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== loader-utils@^1.0.2: version "1.4.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" integrity sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^1.0.1" loader-utils@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^2.1.2" locate-path@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" integrity sha1-K1aLJl7slExtnA3pw9u7ygNUzY4= dependencies: p-locate "^2.0.0" path-exists "^3.0.0" locate-path@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== dependencies: p-locate "^3.0.0" path-exists "^3.0.0" locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== dependencies: p-locate "^4.1.0" lodash.camelcase@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" integrity sha1-soqmKIorn8ZRA1x3EfZathkDMaY= lodash.flatten@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f" integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8= lodash.range@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/lodash.range/-/lodash.range-3.2.0.tgz#f461e588f66683f7eadeade513e38a69a565a15d" integrity sha1-9GHliPZmg/fq3q3lE+OKaaVloV0= lodash@^4.0.0, lodash@^4.17.11, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== dependencies: chalk "^2.0.1" log-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== dependencies: chalk "^2.4.2" log-symbols@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== dependencies: chalk "^4.0.0" log-update@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== dependencies: ansi-escapes "^4.3.0" cli-cursor "^3.1.0" slice-ansi "^4.0.0" wrap-ansi "^6.2.0" longest-streak@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-3.0.0.tgz#f127e2bded83caa6a35ac5f7a2f2b2f94b36f3dc" integrity sha512-XhUjWR5CFaQ03JOP+iSDS9koy8T5jfoImCZ4XprElw3BXsSk4MpVYOLw/6LTDKZhO13PlAXnB5gS4MHQTpkSOw== loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== dependencies: js-tokens "^3.0.0 || ^4.0.0" lowercase-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" make-error@^1.1.1: version "1.3.5" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== [email protected]: version "13.0.1" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-13.0.1.tgz#c6ecc431cacf1a5da531423fc6a42807814af430" integrity sha512-lTlxriVoy2criHP0JKRhO2VDG9c2ypWCsT237eDiLqi09rmbKoUetyGHq2uOIRoRS//kfoJckS0eUzzkDR+k2Q== dependencies: argparse "^2.0.1" entities "~3.0.1" linkify-it "^4.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdown-it@^12.0.0: version "12.3.2" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.3.2.tgz#bf92ac92283fe983fe4de8ff8abfb5ad72cd0c90" integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== dependencies: argparse "^2.0.1" entities "~2.1.0" linkify-it "^3.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdownlint-cli@^0.33.0: version "0.33.0" resolved "https://registry.yarnpkg.com/markdownlint-cli/-/markdownlint-cli-0.33.0.tgz#703af1234c32c309ab52fcd0e8bc797a34e2b096" integrity sha512-zMK1oHpjYkhjO+94+ngARiBBrRDEUMzooDHBAHtmEIJ9oYddd9l3chCReY2mPlecwH7gflQp1ApilTo+o0zopQ== dependencies: commander "~9.4.1" get-stdin "~9.0.0" glob "~8.0.3" ignore "~5.2.4" js-yaml "^4.1.0" jsonc-parser "~3.2.0" markdownlint "~0.27.0" minimatch "~5.1.2" run-con "~1.2.11" markdownlint@~0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.27.0.tgz#9dabf7710a4999e2835e3c68317f1acd0bc89049" integrity sha512-HtfVr/hzJJmE0C198F99JLaeada+646B5SaG2pVoEakLFI6iRGsvMqrnnrflq8hm1zQgwskEgqSnhDW11JBp0w== dependencies: markdown-it "13.0.1" matcher-collection@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/matcher-collection/-/matcher-collection-1.1.2.tgz#1076f506f10ca85897b53d14ef54f90a5c426838" integrity sha512-YQ/teqaOIIfUHedRam08PB3NK7Mjct6BvzRnJmpGDm8uFXpNr1sbY4yuflI5JcEs6COpYA0FpRQhSDBf1tT95g== dependencies: minimatch "^3.0.2" matcher@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca" integrity sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng== dependencies: escape-string-regexp "^4.0.0" mdast-comment-marker@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-comment-marker/-/mdast-comment-marker-1.1.1.tgz#9c9c18e1ed57feafc1965d92b028f37c3c8da70d" integrity sha512-TWZDaUtPLwKX1pzDIY48MkSUQRDwX/HqbTB4m3iYdL/zosi/Z6Xqfdv0C0hNVKvzrPjZENrpWDt4p4odeVO0Iw== mdast-util-from-markdown@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.0.tgz#c517313cd999ec2b8f6d447b438c5a9d500b89c9" integrity sha512-uj2G60sb7z1PNOeElFwCC9b/Se/lFXuLhVKFOAY2EHz/VvgbupTQRNXPoZl7rGpXYL6BNZgcgaybrlSWbo7n/g== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" mdast-util-to-string "^3.0.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" unist-util-stringify-position "^3.0.0" mdast-util-from-markdown@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.2.0.tgz#84df2924ccc6c995dec1e2368b2b208ad0a76268" integrity sha512-iZJyyvKD1+K7QX1b5jXdE7Sc5dtoTry1vzV28UZZe8Z1xVnB/czKntJ7ZAkG0tANqRnBF6p3p7GpU1y19DTf2Q== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" decode-named-character-reference "^1.0.0" mdast-util-to-string "^3.1.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-decode-string "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" unist-util-stringify-position "^3.0.0" uvu "^0.5.0" mdast-util-heading-style@^1.0.2: version "1.0.5" resolved "https://registry.yarnpkg.com/mdast-util-heading-style/-/mdast-util-heading-style-1.0.5.tgz#81b2e60d76754198687db0e8f044e42376db0426" integrity sha512-8zQkb3IUwiwOdUw6jIhnwM6DPyib+mgzQuHAe7j2Hy1rIarU4VUxe472bp9oktqULW3xqZE+Kz6OD4Gi7IA3vw== mdast-util-to-markdown@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-util-to-markdown/-/mdast-util-to-markdown-1.1.1.tgz#545ccc4dcc6672614b84fd1064482320dd689b12" integrity sha512-4puev/CxuxVdlsx5lVmuzgdqfjkkJJLS1Zm/MnejQ8I7BLeeBlbkwp6WOGJypEcN8g56LbVbhNmn84MvvcAvSQ== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" longest-streak "^3.0.0" mdast-util-to-string "^3.0.0" parse-entities "^3.0.0" zwitch "^2.0.0" mdast-util-to-string@^1.0.2: version "1.0.6" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-1.0.6.tgz#7d85421021343b33de1552fc71cb8e5b4ae7536d" integrity sha512-868pp48gUPmZIhfKrLbaDneuzGiw3OTDjHc5M1kAepR2CWBJ+HpEsm252K4aXdiP5coVZaJPOqGtVU6Po8xnXg== mdast-util-to-string@^3.0.0, mdast-util-to-string@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-3.1.0.tgz#56c506d065fbf769515235e577b5a261552d56e9" integrity sha512-n4Vypz/DZgwo0iMHLQL49dJzlp7YtAJP+N07MZHpjPf/5XJuHUWstviF4Mn2jEiR/GNmtnRRqnwsXExk3igfFA== mdurl@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= [email protected]: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g= memory-fs@^0.4.0: version "0.4.1" resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= dependencies: errno "^0.1.3" readable-stream "^2.0.1" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" integrity sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E= merge-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== merge2@^1.3.0: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== methods@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= micromark-core-commonmark@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-1.0.0.tgz#b767fa7687c205c224175bf067796360a3830350" integrity sha512-y9g7zymcKRBHM/aNBekstvs/Grpf+y4OEBULUTYvGZcusnp+JeOxmilJY4GMpo2/xY7iHQL9fjz5pD9pSAud9A== dependencies: micromark-factory-destination "^1.0.0" micromark-factory-label "^1.0.0" micromark-factory-space "^1.0.0" micromark-factory-title "^1.0.0" micromark-factory-whitespace "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-classify-character "^1.0.0" micromark-util-html-tag-name "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromark-factory-destination@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-destination/-/micromark-factory-destination-1.0.0.tgz#fef1cb59ad4997c496f887b6977aa3034a5a277e" integrity sha512-eUBA7Rs1/xtTVun9TmV3gjfPz2wEwgK5R5xcbIM5ZYAtvGF6JkyaDsj0agx8urXnO31tEO6Ug83iVH3tdedLnw== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-label@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz#b316ec479b474232973ff13b49b576f84a6f2cbb" integrity sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-space@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-space/-/micromark-factory-space-1.0.0.tgz#cebff49968f2b9616c0fcb239e96685cb9497633" integrity sha512-qUmqs4kj9a5yBnk3JMLyjtWYN6Mzfcx8uJfi5XAveBniDevmZasdGBba5b4QsvRcAkmvGo5ACmSUmyGiKTLZew== dependencies: micromark-util-character "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-title@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz#708f7a8044f34a898c0efdb4f55e4da66b537273" integrity sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-whitespace@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-whitespace/-/micromark-factory-whitespace-1.0.0.tgz#e991e043ad376c1ba52f4e49858ce0794678621c" integrity sha512-Qx7uEyahU1lt1RnsECBiuEbfr9INjQTGa6Err+gF3g0Tx4YEviPbqqGKNv/NrBaE7dVHdn1bVZKM/n5I/Bak7A== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-character@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/micromark-util-character/-/micromark-util-character-1.1.0.tgz#d97c54d5742a0d9611a68ca0cd4124331f264d86" integrity sha512-agJ5B3unGNJ9rJvADMJ5ZiYjBRyDpzKAOk01Kpi1TKhlT1APx3XZk6eN7RtSz1erbWHC2L8T3xLZ81wdtGRZzg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-chunked@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-chunked/-/micromark-util-chunked-1.0.0.tgz#5b40d83f3d53b84c4c6bce30ed4257e9a4c79d06" integrity sha512-5e8xTis5tEZKgesfbQMKRCyzvffRRUX+lK/y+DvsMFdabAicPkkZV6gO+FEWi9RfuKKoxxPwNL+dFF0SMImc1g== dependencies: micromark-util-symbol "^1.0.0" micromark-util-classify-character@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-classify-character/-/micromark-util-classify-character-1.0.0.tgz#cbd7b447cb79ee6997dd274a46fc4eb806460a20" integrity sha512-F8oW2KKrQRb3vS5ud5HIqBVkCqQi224Nm55o5wYLzY/9PwHGXC01tr3d7+TqHHz6zrKQ72Okwtvm/xQm6OVNZA== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-combine-extensions@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.0.0.tgz#91418e1e74fb893e3628b8d496085639124ff3d5" integrity sha512-J8H058vFBdo/6+AsjHp2NF7AJ02SZtWaVUjsayNFeAiydTxUwViQPxN0Hf8dp4FmCQi0UUFovFsEyRSUmFH3MA== dependencies: micromark-util-chunked "^1.0.0" micromark-util-types "^1.0.0" micromark-util-decode-numeric-character-reference@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.0.0.tgz#dcc85f13b5bd93ff8d2868c3dba28039d490b946" integrity sha512-OzO9AI5VUtrTD7KSdagf4MWgHMtET17Ua1fIpXTpuhclCqD8egFWo85GxSGvxgkGS74bEahvtM0WP0HjvV0e4w== dependencies: micromark-util-symbol "^1.0.0" micromark-util-decode-string@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/micromark-util-decode-string/-/micromark-util-decode-string-1.0.2.tgz#942252ab7a76dec2dbf089cc32505ee2bc3acf02" integrity sha512-DLT5Ho02qr6QWVNYbRZ3RYOSSWWFuH3tJexd3dgN1odEuPNxCngTCXJum7+ViRAd9BbdxCvMToPOD/IvVhzG6Q== dependencies: decode-named-character-reference "^1.0.0" micromark-util-character "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-encode@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-encode/-/micromark-util-encode-1.0.0.tgz#c409ecf751a28aa9564b599db35640fccec4c068" integrity sha512-cJpFVM768h6zkd8qJ1LNRrITfY4gwFt+tziPcIf71Ui8yFzY9wG3snZQqiWVq93PG4Sw6YOtcNiKJfVIs9qfGg== micromark-util-html-tag-name@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.0.0.tgz#75737e92fef50af0c6212bd309bc5cb8dbd489ed" integrity sha512-NenEKIshW2ZI/ERv9HtFNsrn3llSPZtY337LID/24WeLqMzeZhBEE6BQ0vS2ZBjshm5n40chKtJ3qjAbVV8S0g== micromark-util-normalize-identifier@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.0.0.tgz#4a3539cb8db954bbec5203952bfe8cedadae7828" integrity sha512-yg+zrL14bBTFrQ7n35CmByWUTFsgst5JhA4gJYoty4Dqzj4Z4Fr/DHekSS5aLfH9bdlfnSvKAWsAgJhIbogyBg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-resolve-all@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-resolve-all/-/micromark-util-resolve-all-1.0.0.tgz#a7c363f49a0162e931960c44f3127ab58f031d88" integrity sha512-CB/AGk98u50k42kvgaMM94wzBqozSzDDaonKU7P7jwQIuH2RU0TeBqGYJz2WY1UdihhjweivStrJ2JdkdEmcfw== dependencies: micromark-util-types "^1.0.0" micromark-util-sanitize-uri@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.0.0.tgz#27dc875397cd15102274c6c6da5585d34d4f12b2" integrity sha512-cCxvBKlmac4rxCGx6ejlIviRaMKZc0fWm5HdCHEeDWRSkn44l6NdYVRyU+0nT1XC72EQJMZV8IPHF+jTr56lAg== dependencies: micromark-util-character "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-subtokenize@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz#6f006fa719af92776c75a264daaede0fb3943c6a" integrity sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ== dependencies: micromark-util-chunked "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-symbol@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-symbol/-/micromark-util-symbol-1.0.0.tgz#91cdbcc9b2a827c0129a177d36241bcd3ccaa34d" integrity sha512-NZA01jHRNCt4KlOROn8/bGi6vvpEmlXld7EHcRH+aYWUfL3Wc8JLUNNlqUMKa0hhz6GrpUWsHtzPmKof57v0gQ== micromark-util-types@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-types/-/micromark-util-types-1.0.0.tgz#0ebdfaea3fa7c15fc82b1e06ea1ef0152d0fb2f0" integrity sha512-psf1WAaP1B77WpW4mBGDkTr+3RsPuDAgsvlP47GJzbH1jmjH8xjOx7Z6kp84L8oqHmy5pYO3Ev46odosZV+3AA== micromark@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/micromark/-/micromark-3.0.3.tgz#4c9f76fce8ba68eddf8730bb4fee2041d699d5b7" integrity sha512-fWuHx+JKV4zA8WfCFor2DWP9XmsZkIiyWRGofr7P7IGfpRIlb7/C5wwusGsNyr1D8HI5arghZDG1Ikc0FBwS5Q== dependencies: "@types/debug" "^4.0.0" debug "^4.0.0" micromark-core-commonmark "^1.0.0" micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-combine-extensions "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-sanitize-uri "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromatch@^4.0.0, micromatch@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259" integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q== dependencies: braces "^3.0.1" picomatch "^2.0.5" [email protected]: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== mime-types@^2.1.12, mime-types@^2.1.27, mime-types@~2.1.24, mime-types@~2.1.34: version "2.1.35" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== dependencies: mime-db "1.52.0" [email protected]: version "1.6.0" resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== mimic-fn@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== mimic-response@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== mimic-response@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.4: version "3.0.8" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.8.tgz#5e6a59bd11e2ab0de1cfb843eb2d82e546c321c1" integrity sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q== dependencies: brace-expansion "^1.1.7" minimatch@^5.0.1: version "5.1.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.1.tgz#6c9dffcf9927ff2a31e74b5af11adf8b9604b022" integrity sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g== dependencies: brace-expansion "^2.0.1" minimatch@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.2.tgz#0939d7d6f0898acbd1508abe534d1929368a8fff" integrity sha512-bNH9mmM9qsJ2X4r2Nat1B//1dJVcn3+iBLa3IgqJ7EbGaDNepL9QSHOxN4ng33s52VMMhhIfgCYDk3C4ZmlDAg== dependencies: brace-expansion "^2.0.1" minimist@^1.0.0, minimist@^1.2.5, minimist@^1.2.6, minimist@~1.2.0: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minimist@^1.2.0: version "1.2.7" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== minipass@^3.0.0: version "3.3.6" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw== dependencies: yallist "^4.0.0" minipass@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.1.tgz#2b9408c6e81bb8b338d600fb3685e375a370a057" integrity sha512-V9esFpNbK0arbN3fm2sxDKqMYgIp7XtVdE4Esj+PE4Qaaxdg1wIw48ITQIOn1sc8xXSmUviVL3cyjMqPlrVkiA== minizlib@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== dependencies: minipass "^3.0.0" yallist "^4.0.0" mkdirp@^0.5.1: version "0.5.5" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== dependencies: minimist "^1.2.5" mkdirp@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== mri@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= [email protected], ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== [email protected]: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== nan@nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac: version "2.15.0" resolved "https://codeload.github.com/nodejs/nan/tar.gz/16fa32231e2ccd89d2804b3f765319128b20c4ac" natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= [email protected]: version "0.6.3" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== neo-async@^2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-fetch@^2.6.1: version "2.6.8" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.8.tgz#a68d30b162bc1d8fd71a367e81b997e1f4d4937e" integrity sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg== dependencies: whatwg-url "^5.0.0" node-fetch@^2.6.7: version "2.6.7" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad" integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ== dependencies: whatwg-url "^5.0.0" node-releases@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503" integrity sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg== normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" resolve "^1.10.0" semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== normalize-url@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== npm-run-path@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: path-key "^3.0.0" null-loader@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-4.0.0.tgz#8e491b253cd87341d82c0e84b66980d806dfbd04" integrity sha512-vSoBF6M08/RHwc6r0gvB/xBJBtmbvvEkf6+IiadUCoNYchjxE8lwzCGFg0Qp2D25xPiJxUBh2iNWzlzGMILp7Q== dependencies: loader-utils "^2.0.0" schema-utils "^2.6.5" object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= object-inspect@^1.7.0: version "1.8.0" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.8.0.tgz#df807e5ecf53a609cc6bfe93eac3cc7be5b3a9d0" integrity sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA== object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g== object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object.assign@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== dependencies: define-properties "^1.1.2" function-bind "^1.1.1" has-symbols "^1.0.0" object-keys "^1.0.11" object.entries@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" has "^1.0.3" object.fromentries@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" integrity sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" object.values@^1.1.0, object.values@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.1.tgz#68a99ecde356b7e9295a3c5e0ce31dc8c953de5e" integrity sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" [email protected]: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== dependencies: ee-first "1.1.1" once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" onetime@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" integrity sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ= dependencies: mimic-fn "^1.0.0" onetime@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.0.tgz#fff0f3c91617fe62bb50189636e99ac8a6df7be5" integrity sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q== dependencies: mimic-fn "^2.1.0" optionator@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== dependencies: deep-is "~0.1.3" fast-levenshtein "~2.0.6" levn "~0.3.0" prelude-ls "~1.1.2" type-check "~0.3.2" word-wrap "~1.2.3" optionator@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== dependencies: deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" word-wrap "^1.2.3" ora@^3.4.0: version "3.4.0" resolved "https://registry.yarnpkg.com/ora/-/ora-3.4.0.tgz#bf0752491059a3ef3ed4c85097531de9fdbcd318" integrity sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg== dependencies: chalk "^2.4.2" cli-cursor "^2.1.0" cli-spinners "^2.0.0" log-symbols "^2.2.0" strip-ansi "^5.2.0" wcwidth "^1.0.1" ora@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.3.tgz#752a1b7b4be4825546a7a3d59256fa523b6b6d05" integrity sha512-fnDebVFyz309A73cqCipVL1fBZewq4vwgSHfxh43vVy31mbyoQ8sCH3Oeaog/owYOs/lLlGVPCISQonTneg6Pg== dependencies: chalk "^3.0.0" cli-cursor "^3.1.0" cli-spinners "^2.2.0" is-interactive "^1.0.0" log-symbols "^3.0.0" mute-stream "0.0.8" strip-ansi "^6.0.0" wcwidth "^1.0.1" os-tmpdir@^1.0.0, os-tmpdir@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= p-cancelable@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== p-limit@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8" integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q== dependencies: p-try "^1.0.0" p-limit@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2" integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ== dependencies: p-try "^2.0.0" p-limit@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" p-locate@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" integrity sha1-IKAQOyIqcMj9OcwuWAaA893l7EM= dependencies: p-limit "^1.1.0" p-locate@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== dependencies: p-limit "^2.0.0" p-locate@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== dependencies: p-limit "^2.2.0" p-map@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b" integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== dependencies: aggregate-error "^3.0.0" p-try@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3" integrity sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M= p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== parent-module@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== dependencies: callsites "^3.0.0" parse-entities@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-3.0.0.tgz#9ed6d6569b6cfc95ade058d683ddef239dad60dc" integrity sha512-AJlcIFDNPEP33KyJLguv0xJc83BNvjxwpuUIcetyXUsLpVXAUCePJ5kIoYtEN2R1ac0cYaRu/vk9dVFkewHQhQ== dependencies: character-entities "^2.0.0" character-entities-legacy "^2.0.0" character-reference-invalid "^2.0.0" is-alphanumerical "^2.0.0" is-decimal "^2.0.0" is-hexadecimal "^2.0.0" parse-gitignore@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/parse-gitignore/-/parse-gitignore-0.4.0.tgz#abf702e4b900524fff7902b683862857b63f93fe" integrity sha1-q/cC5LkAUk//eQK2g4YoV7Y/k/4= dependencies: array-unique "^0.3.2" is-glob "^3.1.0" parse-json@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= dependencies: error-ex "^1.2.0" parse-json@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= dependencies: error-ex "^1.3.1" json-parse-better-errors "^1.0.1" parse-json@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.0.0.tgz#73e5114c986d143efa3712d4ea24db9a4266f60f" integrity sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw== dependencies: "@babel/code-frame" "^7.0.0" error-ex "^1.3.1" json-parse-better-errors "^1.0.1" lines-and-columns "^1.1.6" parse-ms@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-key@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== path-parse@^1.0.6, path-parse@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== [email protected]: version "0.1.7" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w= path-type@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-2.0.0.tgz#f012ccb8415b7096fc2daa1054c3d72389594c73" integrity sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM= dependencies: pify "^2.0.0" path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== pathval@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pathval/-/pathval-1.1.1.tgz#8534e77a77ce7ac5a2512ea21e0fdb8fcf6c3d8d" integrity sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ== pend@~1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg== picocolors@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== picomatch@^2.0.4, picomatch@^2.0.5: version "2.0.7" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.0.7.tgz#514169d8c7cd0bdbeecc8a2609e34a7163de69f6" integrity sha512-oLHIdio3tZ0qH76NybpeneBhYVj0QFTfXEFTc/B3zKQspYfYYkWYgFsmzo+4kvId/bQRcNkVeguI3y+CD22BtA== picomatch@^2.2.1: version "2.2.2" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== picomatch@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== pify@^2.0.0: version "2.3.0" resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= pify@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== pkg-conf@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pkg-conf/-/pkg-conf-3.1.0.tgz#d9f9c75ea1bae0e77938cde045b276dac7cc69ae" integrity sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ== dependencies: find-up "^3.0.0" load-json-file "^5.2.0" pkg-config@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pkg-config/-/pkg-config-1.1.1.tgz#557ef22d73da3c8837107766c52eadabde298fe4" integrity sha1-VX7yLXPaPIg3EHdmxS6tq94pj+Q= dependencies: debug-log "^1.0.0" find-root "^1.0.0" xtend "^4.0.1" pkg-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-2.0.0.tgz#f6d5d1109e19d63edf428e0bd57e12777615334b" integrity sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s= dependencies: find-up "^2.1.0" pkg-dir@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== dependencies: find-up "^4.0.0" please-upgrade-node@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz#aeddd3f994c933e4ad98b99d9a556efa0e2fe942" integrity sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg== dependencies: semver-compare "^1.0.0" pluralize@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== pre-flight@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pre-flight/-/pre-flight-1.1.1.tgz#482fb1649fb400616a86b2706b11591f5cc8402d" integrity sha512-glqyc2Hh3K+sYeSsVs+HhjyUVf8j6xwuFej0yjYjRYfSnOK8P3Na9GznkoPn48fR+9kTOfkocYIWrtWktp4AqA== dependencies: colors "^1.1.2" commander "^2.9.0" semver "^5.1.0" prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== prelude-ls@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= pretty-ms@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.0.0.tgz#6133a8f55804b208e4728f6aa7bf01085e951e24" integrity sha512-94VRYjL9k33RzfKiGokPBPpsmloBYSf5Ri+Pq19zlsEcUKFob+admeXr5eFDRuPjFmEOcjJvPGdillYOJyvZ7Q== dependencies: parse-ms "^2.1.0" pretty-ms@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.1.0.tgz#b906bdd1ec9e9799995c372e2b1c34f073f95384" integrity sha512-4gaK1skD2gwscCfkswYQRmddUb2GJZtzDGRjHWadVHtK/DIKFufa12MvES6/xu1tVbUYeia5bmLcwJtZJQUqnw== dependencies: parse-ms "^2.1.0" process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== process@^0.11.10, process@~0.11.0: version "0.11.10" resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== progress@^2.0.0, progress@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== prop-types@^15.7.2: version "15.7.2" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== dependencies: loose-envify "^1.4.0" object-assign "^4.1.1" react-is "^16.8.1" proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= pump@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== dependencies: end-of-stream "^1.1.0" once "^1.3.1" [email protected]: version "1.3.2" resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" integrity sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw== punycode@^2.1.0: version "2.1.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== [email protected]: version "6.11.0" resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q== dependencies: side-channel "^1.0.4" [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g== quick-lru@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-5.1.1.tgz#366493e6b3e42a3a6885e2e99d18f80fb7a8c932" integrity sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA== ramda@^0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.27.0.tgz#915dc29865c0800bf3f69b8fd6c279898b59de43" integrity sha512-pVzZdDpWwWqEVVLshWUHjNwuVP7SfcmPraYuqocJp1yo2U1R7P+5QAfDhdItkuoGqIBnBYrtPp7rEPqDn9HlZA== randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== dependencies: safe-buffer "^5.1.0" range-parser@~1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== [email protected]: version "2.5.1" resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.1.tgz#fe1b1628b181b700215e5fd42389f98b71392857" integrity sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig== dependencies: bytes "3.1.2" http-errors "2.0.0" iconv-lite "0.4.24" unpipe "1.0.0" react-is@^16.8.1: version "16.8.6" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== read-pkg-up@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-2.0.0.tgz#6b72a8048984e0c41e79510fd5e9fa99b3b549be" integrity sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4= dependencies: find-up "^2.0.0" read-pkg "^2.0.0" read-pkg@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-2.0.0.tgz#8ef1c0623c6a6db0dc6713c4bfac46332b2368f8" integrity sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg= dependencies: load-json-file "^2.0.0" normalize-package-data "^2.3.2" path-type "^2.0.0" readable-stream@^2, readable-stream@^2.0.1, readable-stream@~2.3.6: version "2.3.6" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" isarray "~1.0.0" process-nextick-args "~2.0.0" safe-buffer "~5.1.1" string_decoder "~1.1.1" util-deprecate "~1.0.1" readable-stream@^3.0.2: version "3.6.0" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: inherits "^2.0.3" string_decoder "^1.1.1" util-deprecate "^1.0.1" readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== dependencies: picomatch "^2.2.1" rechoir@^0.6.2: version "0.6.2" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= dependencies: resolve "^1.1.6" rechoir@^0.7.0: version "0.7.1" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== dependencies: resolve "^1.9.0" regexpp@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-2.0.1.tgz#8d19d31cf632482b589049f8281f93dbcba4d07f" integrity sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw== regexpp@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.0.0.tgz#dd63982ee3300e67b41c1956f850aa680d9d330e" integrity sha512-Z+hNr7RAVWxznLPuA7DIh8UNX1j9CDrUQxskw9IrBE1Dxue2lyXT+shqEIeLUjrokxIP8CMy1WkjgG3rTsd5/g== regexpp@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== remark-cli@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-cli/-/remark-cli-10.0.0.tgz#3b0e20f2ad3909f35c7a6fb3f721c82f6ff5beac" integrity sha512-Yc5kLsJ5vgiQJl6xMLLJHqPac6OSAC5DOqKQrtmzJxSdJby2Jgr+OpIAkWQYwvbNHEspNagyoQnuwK2UCWg73g== dependencies: remark "^14.0.0" unified-args "^9.0.0" remark-lint-blockquote-indentation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-blockquote-indentation/-/remark-lint-blockquote-indentation-2.0.1.tgz#27347959acf42a6c3e401488d8210e973576b254" integrity sha512-uJ9az/Ms9AapnkWpLSCJfawBfnBI2Tn1yUsPNqIFv6YM98ymetItUMyP6ng9NFPqDvTQBbiarulkgoEo0wcafQ== dependencies: mdast-util-to-string "^1.0.2" pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-code-block-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-code-block-style/-/remark-lint-code-block-style-2.0.1.tgz#448b0f2660acfcdfff2138d125ff5b1c1279c0cb" integrity sha512-eRhmnColmSxJhO61GHZkvO67SpHDshVxs2j3+Zoc5Y1a4zQT2133ZAij04XKaBFfsVLjhbY/+YOWxgvtjx2nmA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-case@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-case/-/remark-lint-definition-case-2.0.1.tgz#10340eb2f87acff41140d52ad7e5b40b47e6690a" integrity sha512-M+XlThtQwEJLQnQb5Gi6xZdkw92rGp7m2ux58WMw/Qlcg02WgHR/O0OcHPe5VO5hMJrtI+cGG5T0svsCgRZd3w== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-spacing@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-spacing/-/remark-lint-definition-spacing-2.0.1.tgz#97f01bf9bf77a7bdf8013b124b7157dd90b07c64" integrity sha512-xK9DOQO5MudITD189VyUiMHBIKltW1oc55L7Fti3i9DedXoBG7Phm+V9Mm7IdWzCVkquZVgVk63xQdqzSQRrSQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-emphasis-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-emphasis-marker/-/remark-lint-emphasis-marker-2.0.1.tgz#1d5ca2070d4798d16c23120726158157796dc317" integrity sha512-7mpbAUrSnHiWRyGkbXRL5kfSKY9Cs8cdob7Fw+Z02/pufXMF4yRWaegJ5NTUu1RE+SKlF44wtWWjvcIoyY6/aw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-flag@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-flag/-/remark-lint-fenced-code-flag-2.0.1.tgz#2cb3ddb1157082c45760c7d01ca08e13376aaf62" integrity sha512-+COnWHlS/h02FMxoZWxNlZW3Y8M0cQQpmx3aNCbG7xkyMyCKsMLg9EmRvYHHIbxQCuF3JT0WWx5AySqlc7d+NA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-marker/-/remark-lint-fenced-code-marker-2.0.1.tgz#7bbeb0fb45b0818a3c8a2d232cf0c723ade58ecf" integrity sha512-lujpjm04enn3ma6lITlttadld6eQ1OWAEcT3qZzvFHp+zPraC0yr0eXlvtDN/0UH8mrln/QmGiZp3i8IdbucZg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-file-extension@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-file-extension/-/remark-lint-file-extension-1.0.3.tgz#a7fc78fbf041e513c618b2cca0f2160ee37daa13" integrity sha512-P5gzsxKmuAVPN7Kq1W0f8Ss0cFKfu+OlezYJWXf+5qOa+9Y5GqHEUOobPnsmNFZrVMiM7JoqJN2C9ZjrUx3N6Q== dependencies: unified-lint-rule "^1.0.0" remark-lint-final-definition@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/remark-lint-final-definition/-/remark-lint-final-definition-2.1.0.tgz#b6e654c01ebcb1afc936d7b9cd74db8ec273e0bb" integrity sha512-83K7n2icOHPfBzbR5Mr1o7cu8gOjD8FwJkFx/ly+rW+8SHfjCj4D3WOFGQ1xVdmHjfomBDXXDSNo2oiacADVXQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-hard-break-spaces@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-hard-break-spaces/-/remark-lint-hard-break-spaces-2.0.1.tgz#2149b55cda17604562d040c525a2a0d26aeb0f0f" integrity sha512-Qfn/BMQFamHhtbfLrL8Co/dbYJFLRL4PGVXZ5wumkUO5f9FkZC2RsV+MD9lisvGTkJK0ZEJrVVeaPbUIFM0OAw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-heading-increment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-increment/-/remark-lint-heading-increment-2.0.1.tgz#b578f251508a05d79bc2d1ae941e0620e23bf1d3" integrity sha512-bYDRmv/lk3nuWXs2VSD1B4FneGT6v7a74FuVmb305hyEMmFSnneJvVgnOJxyKlbNlz12pq1IQ6MhlJBda/SFtQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-heading-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-style/-/remark-lint-heading-style-2.0.1.tgz#8216fca67d97bbbeec8a19b6c71bfefc16549f72" integrity sha512-IrFLNs0M5Vbn9qg51AYhGUfzgLAcDOjh2hFGMz3mx664dV6zLcNZOPSdJBBJq3JQR4gKpoXcNwN1+FFaIATj+A== dependencies: mdast-util-heading-style "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-link-title-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-link-title-style/-/remark-lint-link-title-style-2.0.1.tgz#51a595c69fcfa73a245a030dfaa3504938a1173a" integrity sha512-+Q7Ew8qpOQzjqbDF6sUHmn9mKgje+m2Ho8Xz7cEnGIRaKJgtJzkn/dZqQM/az0gn3zaN6rOuwTwqw4EsT5EsIg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-list-item-content-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-content-indent/-/remark-lint-list-item-content-indent-2.0.1.tgz#96387459440dcd61e522ab02bff138b32bfaa63a" integrity sha512-OzUMqavxyptAdG7vWvBSMc9mLW9ZlTjbW4XGayzczd3KIr6Uwp3NEFXKx6MLtYIM/vwBqMrPQUrObOC7A2uBpQ== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-indent/-/remark-lint-list-item-indent-2.0.1.tgz#c6472514e17bc02136ca87936260407ada90bf8d" integrity sha512-4IKbA9GA14Q9PzKSQI6KEHU/UGO36CSQEjaDIhmb9UOhyhuzz4vWhnSIsxyI73n9nl9GGRAMNUSGzr4pQUFwTA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-spacing@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-list-item-spacing/-/remark-lint-list-item-spacing-3.0.0.tgz#14c18fe8c0f19231edb5cf94abda748bb773110b" integrity sha512-SRUVonwdN3GOSFb6oIYs4IfJxIVR+rD0nynkX66qEO49/qDDT1PPvkndis6Nyew5+t+2V/Db9vqllL6SWbnEtw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-maximum-heading-length@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-maximum-heading-length/-/remark-lint-maximum-heading-length-2.0.1.tgz#56f240707a75b59bce3384ccc9da94548affa98f" integrity sha512-1CjJ71YDqEpoOjUnc4wrwZV8ZGXWUIYRYeGoarAy3QKHepJL9M+zkdbOxZDfhc3tjVoDW/LWcgsW+DEpczgiMA== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-maximum-line-length@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/remark-lint-maximum-line-length/-/remark-lint-maximum-line-length-2.0.3.tgz#d0d15410637d61b031a83d7c78022ec46d6c858a" integrity sha512-zyWHBFh1oPAy+gkaVFXiTHYP2WwriIeBtaarDqkweytw0+qmuikjVMJTWbQ3+XfYBreD7KKDM9SI79nkp0/IZQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-auto-link-without-protocol@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-2.0.1.tgz#f75e5c24adb42385593e0d75ca39987edb70b6c4" integrity sha512-TFcXxzucsfBb/5uMqGF1rQA+WJJqm1ZlYQXyvJEXigEZ8EAxsxZGPb/gOQARHl/y0vymAuYxMTaChavPKaBqpQ== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-blockquote-without-marker@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-4.0.0.tgz#856fb64dd038fa8fc27928163caa24a30ff4d790" integrity sha512-Y59fMqdygRVFLk1gpx2Qhhaw5IKOR9T38Wf7pjR07bEFBGUNfcoNVIFMd1TCJfCPQxUyJzzSqfZz/KT7KdUuiQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-no-consecutive-blank-lines@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-consecutive-blank-lines/-/remark-lint-no-consecutive-blank-lines-3.0.0.tgz#c8fe11095b8f031a1406da273722bd4a9174bf41" integrity sha512-kmzLlOLrapBKEngwYFTdCZDmeOaze6adFPB7G0EdymD9V1mpAlnneINuOshRLEDKK5fAhXKiZXxdGIaMPkiXrA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-duplicate-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-duplicate-headings/-/remark-lint-no-duplicate-headings-2.0.1.tgz#4a4b70e029155ebcfc03d8b2358c427b69a87576" integrity sha512-F6AP0FJcHIlkmq0pHX0J5EGvLA9LfhuYTvnNO8y3kvflHeRjFkDyt2foz/taXR8OcLQR51n/jIJiwrrSMbiauw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-emphasis-as-heading@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-emphasis-as-heading/-/remark-lint-no-emphasis-as-heading-2.0.1.tgz#fcc064133fe00745943c334080fed822f72711ea" integrity sha512-z86+yWtVivtuGIxIC4g9RuATbgZgOgyLcnaleonJ7/HdGTYssjJNyqCJweaWSLoaI0akBQdDwmtJahW5iuX3/g== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-file-name-articles@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-articles/-/remark-lint-no-file-name-articles-1.0.3.tgz#c712d06a24e24b0c4c3666cf3084a0052a2c2c17" integrity sha512-YZDJDKUWZEmhrO6tHB0u0K0K2qJKxyg/kryr14OaRMvWLS62RgMn97sXPZ38XOSN7mOcCnl0k7/bClghJXx0sg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-consecutive-dashes@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-consecutive-dashes/-/remark-lint-no-file-name-consecutive-dashes-1.0.3.tgz#6a96ddf60e18dcdb004533733f3ccbfd8ab076ae" integrity sha512-7f4vyXn/ca5lAguWWC3eu5hi8oZ7etX7aQlnTSgQZeslnJCbVJm6V6prFJKAzrqbBzMicUXr5pZLBDoXyTvHHw== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-irregular-characters@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-irregular-characters/-/remark-lint-no-file-name-irregular-characters-1.0.3.tgz#6dcd8b51e00e10094585918cb8e7fc999df776c3" integrity sha512-b4xIy1Yi8qZpM2vnMN+6gEujagPGxUBAs1judv6xJQngkl5d5zT8VQZsYsTGHku4NWHjjh3b7vK5mr0/yp4JSg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-mixed-case@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-mixed-case/-/remark-lint-no-file-name-mixed-case-1.0.3.tgz#0ebe5eedd0191507d27ad6ac5eed1778cb33c2de" integrity sha512-d7rJ4c8CzDbEbGafw2lllOY8k7pvnsO77t8cV4PHFylwQ3hmCdTHLuDvK87G3DaWCeKclp0PMyamfOgJWKMkPA== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-outer-dashes@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-outer-dashes/-/remark-lint-no-file-name-outer-dashes-1.0.4.tgz#c6e22a5cc64df4e12fc31712a927e8039854a666" integrity sha512-+bZvvme2Bm3Vp5L2iKuvGHYVmHKrTkkRt8JqJPGepuhvBvT4Q7+CgfKyMtC/hIjyl+IcuJQ2H0qPRzdicjy1wQ== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-heading-punctuation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-heading-punctuation/-/remark-lint-no-heading-punctuation-2.0.1.tgz#face59f9a95c8aa278a8ee0c728bc44cd53ea9ed" integrity sha512-lY/eF6GbMeGu4cSuxfGHyvaQQBIq/6T/o+HvAR5UfxSTxmxZFwbZneAI2lbeR1zPcqOU87NsZ5ZZzWVwdLpPBw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-inline-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-inline-padding/-/remark-lint-no-inline-padding-3.0.0.tgz#14c2722bcddc648297a54298107a922171faf6eb" integrity sha512-3s9uW3Yux9RFC0xV81MQX3bsYs+UY7nPnRuMxeIxgcVwxQ4E/mTJd9QjXUwBhU9kdPtJ5AalngdmOW2Tgar8Cg== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-literal-urls@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-literal-urls/-/remark-lint-no-literal-urls-2.0.1.tgz#731908f9866c1880e6024dcee1269fb0f40335d6" integrity sha512-IDdKtWOMuKVQIlb1CnsgBoyoTcXU3LppelDFAIZePbRPySVHklTtuK57kacgU5grc7gPM04bZV96eliGrRU7Iw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-multiple-toplevel-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-multiple-toplevel-headings/-/remark-lint-no-multiple-toplevel-headings-2.0.1.tgz#3ff2b505adf720f4ff2ad2b1021f8cfd50ad8635" integrity sha512-VKSItR6c+u3OsE5pUiSmNusERNyQS9Nnji26ezoQ1uvy06k3RypIjmzQqJ/hCkSiF+hoyC3ibtrrGT8gorzCmQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-shell-dollars@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/remark-lint-no-shell-dollars/-/remark-lint-no-shell-dollars-2.0.2.tgz#b2c6c3ed95e5615f8e5f031c7d271a18dc17618e" integrity sha512-zhkHZOuyaD3r/TUUkkVqW0OxsR9fnSrAnHIF63nfJoAAUezPOu8D1NBsni6rX8H2DqGbPYkoeWrNsTwiKP0yow== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-image@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-image/-/remark-lint-no-shortcut-reference-image-2.0.1.tgz#d174d12a57e8307caf6232f61a795bc1d64afeaa" integrity sha512-2jcZBdnN6ecP7u87gkOVFrvICLXIU5OsdWbo160FvS/2v3qqqwF2e/n/e7D9Jd+KTq1mR1gEVVuTqkWWuh3cig== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-link@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-link/-/remark-lint-no-shortcut-reference-link-2.0.1.tgz#8f963f81036e45cfb7061b3639e9c6952308bc94" integrity sha512-pTZbslG412rrwwGQkIboA8wpBvcjmGFmvugIA+UQR+GfFysKtJ5OZMPGJ98/9CYWjw9Z5m0/EktplZ5TjFjqwA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-table-indentation@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-table-indentation/-/remark-lint-no-table-indentation-3.0.0.tgz#f3c3fc24375069ec8e510f43050600fb22436731" integrity sha512-+l7GovI6T+3LhnTtz/SmSRyOb6Fxy6tmaObKHrwb/GAebI/4MhFS1LVo3vbiP/RpPYtyQoFbbuXI55hqBG4ibQ== dependencies: unified-lint-rule "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-ordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-style/-/remark-lint-ordered-list-marker-style-2.0.1.tgz#183c31967e6f2ae8ef00effad03633f7fd00ffaa" integrity sha512-Cnpw1Dn9CHn+wBjlyf4qhPciiJroFOEGmyfX008sQ8uGoPZsoBVIJx76usnHklojSONbpjEDcJCjnOvfAcWW1A== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-ordered-list-marker-value@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-value/-/remark-lint-ordered-list-marker-value-2.0.1.tgz#0de343de2efb41f01eae9f0f7e7d30fe43db5595" integrity sha512-blt9rS7OKxZ2NW8tqojELeyNEwPhhTJGVa+YpUkdEH+KnrdcD7Nzhnj6zfLWOx6jFNZk3jpq5nvLFAPteHaNKg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-rule-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-rule-style/-/remark-lint-rule-style-2.0.1.tgz#f59bd82e75d3eaabd0eee1c8c0f5513372eb553c" integrity sha512-hz4Ff9UdlYmtO6Czz99WJavCjqCer7Cav4VopXt+yVIikObw96G5bAuLYcVS7hvMUGqC9ZuM02/Y/iq9n8pkAg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-strong-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-strong-marker/-/remark-lint-strong-marker-2.0.1.tgz#1ad8f190c6ac0f8138b638965ccf3bcd18f6d4e4" integrity sha512-8X2IsW1jZ5FmW9PLfQjkL0OVy/J3xdXLcZrG1GTeQKQ91BrPFyEZqUM2oM6Y4S6LGtxWer+neZkPZNroZoRPBQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-cell-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-cell-padding/-/remark-lint-table-cell-padding-3.0.0.tgz#a769ba1999984ff5f90294fb6ccb8aead7e8a12f" integrity sha512-sEKrbyFZPZpxI39R8/r+CwUrin9YtyRwVn0SQkNQEZWZcIpylK+bvoKIldvLIXQPob+ZxklL0GPVRzotQMwuWQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipe-alignment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-table-pipe-alignment/-/remark-lint-table-pipe-alignment-2.0.1.tgz#12b7e4c54473d69c9866cb33439c718d09cffcc5" integrity sha512-O89U7bp0ja6uQkT2uQrNB76GaPvFabrHiUGhqEUnld21yEdyj7rgS57kn84lZNSuuvN1Oor6bDyCwWQGzzpoOQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-pipes/-/remark-lint-table-pipes-3.0.0.tgz#b30b055d594cae782667eec91c6c5b35928ab259" integrity sha512-QPokSazEdl0Y8ayUV9UB0Ggn3Jos/RAQwIo0z1KDGnJlGDiF80Jc6iU9RgDNUOjlpQffSLIfSVxH5VVYF/K3uQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-unordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-unordered-list-marker-style/-/remark-lint-unordered-list-marker-style-2.0.1.tgz#e64692aa9594dbe7e945ae76ab2218949cd92477" integrity sha512-8KIDJNDtgbymEvl3LkrXgdxPMTOndcux3BHhNGB2lU4UnxSpYeHsxcDgirbgU6dqCAfQfvMjPvfYk19QTF9WZA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/remark-lint/-/remark-lint-8.0.0.tgz#6e40894f4a39eaea31fc4dd45abfaba948bf9a09" integrity sha512-ESI8qJQ/TIRjABDnqoFsTiZntu+FRifZ5fJ77yX63eIDijl/arvmDvT+tAf75/Nm5BFL4R2JFUtkHRGVjzYUsg== dependencies: remark-message-control "^6.0.0" remark-message-control@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/remark-message-control/-/remark-message-control-6.0.0.tgz#955b054b38c197c9f2e35b1d88a4912949db7fc5" integrity sha512-k9bt7BYc3G7YBdmeAhvd3VavrPa/XlKWR3CyHjr4sLO9xJyly8WHHT3Sp+8HPR8lEUv+/sZaffL7IjMLV0f6BA== dependencies: mdast-comment-marker "^1.0.0" unified-message-control "^3.0.0" remark-parse@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-parse/-/remark-parse-10.0.0.tgz#65e2b2b34d8581d36b97f12a2926bb2126961cb4" integrity sha512-07ei47p2Xl7Bqbn9H2VYQYirnAFJPwdMuypdozWsSbnmrkgA2e2sZLZdnDNrrsxR4onmIzH/J6KXqKxCuqHtPQ== dependencies: "@types/mdast" "^3.0.0" mdast-util-from-markdown "^1.0.0" unified "^10.0.0" remark-preset-lint-markdown-style-guide@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-preset-lint-markdown-style-guide/-/remark-preset-lint-markdown-style-guide-4.0.0.tgz#976b6ffd7f37aa90868e081a69241fcde3a297d4" integrity sha512-gczDlfZ28Fz0IN/oddy0AH4CiTu9S8d3pJWUsrnwFiafjhJjPGobGE1OD3bksi53md1Bp4K0fzo99YYfvB4Sjw== dependencies: remark-lint "^8.0.0" remark-lint-blockquote-indentation "^2.0.0" remark-lint-code-block-style "^2.0.0" remark-lint-definition-case "^2.0.0" remark-lint-definition-spacing "^2.0.0" remark-lint-emphasis-marker "^2.0.0" remark-lint-fenced-code-flag "^2.0.0" remark-lint-fenced-code-marker "^2.0.0" remark-lint-file-extension "^1.0.0" remark-lint-final-definition "^2.0.0" remark-lint-hard-break-spaces "^2.0.0" remark-lint-heading-increment "^2.0.0" remark-lint-heading-style "^2.0.0" remark-lint-link-title-style "^2.0.0" remark-lint-list-item-content-indent "^2.0.0" remark-lint-list-item-indent "^2.0.0" remark-lint-list-item-spacing "^3.0.0" remark-lint-maximum-heading-length "^2.0.0" remark-lint-maximum-line-length "^2.0.0" remark-lint-no-auto-link-without-protocol "^2.0.0" remark-lint-no-blockquote-without-marker "^4.0.0" remark-lint-no-consecutive-blank-lines "^3.0.0" remark-lint-no-duplicate-headings "^2.0.0" remark-lint-no-emphasis-as-heading "^2.0.0" remark-lint-no-file-name-articles "^1.0.0" remark-lint-no-file-name-consecutive-dashes "^1.0.0" remark-lint-no-file-name-irregular-characters "^1.0.0" remark-lint-no-file-name-mixed-case "^1.0.0" remark-lint-no-file-name-outer-dashes "^1.0.0" remark-lint-no-heading-punctuation "^2.0.0" remark-lint-no-inline-padding "^3.0.0" remark-lint-no-literal-urls "^2.0.0" remark-lint-no-multiple-toplevel-headings "^2.0.0" remark-lint-no-shell-dollars "^2.0.0" remark-lint-no-shortcut-reference-image "^2.0.0" remark-lint-no-shortcut-reference-link "^2.0.0" remark-lint-no-table-indentation "^3.0.0" remark-lint-ordered-list-marker-style "^2.0.0" remark-lint-ordered-list-marker-value "^2.0.0" remark-lint-rule-style "^2.0.0" remark-lint-strong-marker "^2.0.0" remark-lint-table-cell-padding "^3.0.0" remark-lint-table-pipe-alignment "^2.0.0" remark-lint-table-pipes "^3.0.0" remark-lint-unordered-list-marker-style "^2.0.0" remark-stringify@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-10.0.0.tgz#7f23659d92b2d5da489e3c858656d7bbe045f161" integrity sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA== dependencies: "@types/mdast" "^3.0.0" mdast-util-to-markdown "^1.0.0" unified "^10.0.0" remark@^14.0.0: version "14.0.1" resolved "https://registry.yarnpkg.com/remark/-/remark-14.0.1.tgz#a97280d4f2a3010a7d81e6c292a310dcd5554d80" integrity sha512-7zLG3u8EUjOGuaAS9gUNJPD2j+SqDqAFHv2g6WMpE5CU9rZ6e3IKDM12KHZ3x+YNje+NMAuN55yx8S5msGSx7Q== dependencies: "@types/mdast" "^3.0.0" remark-parse "^10.0.0" remark-stringify "^10.0.0" unified "^10.0.0" repeat-string@^1.0.0: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= requireindex@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.1.0.tgz#e5404b81557ef75db6e49c5a72004893fe03e162" integrity sha1-5UBLgVV+91225JxacgBIk/4D4WI= resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" integrity sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g== resolve-cwd@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== dependencies: resolve-from "^5.0.0" resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== resolve-from@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== resolve@^1.1.6: version "1.21.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.21.0.tgz#b51adc97f3472e6a5cf4444d34bc9d6b9037591f" integrity sha512-3wCbTpk5WJlyE4mSOtDLhqQmGFi0/TD9VPwmiolnk8U0wRgMEktqCXd3vy5buTO3tljvalNvKrjHEfrd2WpEKA== dependencies: is-core-module "^2.8.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" resolve@^1.10.0: version "1.11.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e" integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw== dependencies: path-parse "^1.0.6" resolve@^1.10.1, resolve@^1.11.0, resolve@^1.13.1, resolve@^1.17.0: version "1.17.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== dependencies: path-parse "^1.0.6" resolve@^1.9.0: version "1.22.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177" integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw== dependencies: is-core-module "^2.9.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" responselike@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/responselike/-/responselike-2.0.0.tgz#26391bcc3174f750f9a79eacc40a12a5c42d7723" integrity sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw== dependencies: lowercase-keys "^2.0.0" restore-cursor@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" integrity sha1-n37ih/gv0ybU/RYpI9YhKe7g368= dependencies: onetime "^2.0.0" signal-exit "^3.0.2" restore-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== dependencies: onetime "^5.1.0" signal-exit "^3.0.2" reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== [email protected]: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== dependencies: glob "^7.1.3" rimraf@~2.2.6: version "2.2.8" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.8.tgz#e439be2aaee327321952730f99a8929e4fc50582" integrity sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI= roarr@^2.15.3: version "2.15.4" resolved "https://registry.yarnpkg.com/roarr/-/roarr-2.15.4.tgz#f5fe795b7b838ccfe35dc608e0282b9eba2e7afd" integrity sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A== dependencies: boolean "^3.0.1" detect-node "^2.0.4" globalthis "^1.0.1" json-stringify-safe "^5.0.1" semver-compare "^1.0.0" sprintf-js "^1.1.2" run-async@^2.4.0: version "2.4.1" resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" integrity sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ== run-con@~1.2.11: version "1.2.11" resolved "https://registry.yarnpkg.com/run-con/-/run-con-1.2.11.tgz#0014ed430bad034a60568dfe7de2235f32e3f3c4" integrity sha512-NEMGsUT+cglWkzEr4IFK21P4Jca45HqiAbIIZIBdX5+UZTB24Mb/21iNGgz9xZa8tL6vbW7CXmq7MFN42+VjNQ== dependencies: deep-extend "^0.6.0" ini "~3.0.0" minimist "^1.2.6" strip-json-comments "~3.1.1" run-parallel@^1.1.2, run-parallel@^1.1.9: version "1.1.9" resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679" integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q== rxjs@^6.5.5, rxjs@^6.6.0: version "6.6.0" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.6.0.tgz#af2901eedf02e3a83ffa7f886240ff9018bbec84" integrity sha512-3HMA8z/Oz61DUHe+SdOiQyzIf4tOx5oQHmMir7IZEu6TMqCLHT4LRcmNaUS0NwOz8VLvmmBduMsoaUvMaIiqzg== dependencies: tslib "^1.9.0" sade@^1.7.3: version "1.8.1" resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701" integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A== dependencies: mri "^1.1.0" [email protected], safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== "safer-buffer@>= 2.1.2 < 3": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== sax@>=0.6.0: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== schema-utils@^2.6.5: version "2.7.0" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.7.0.tgz#17151f76d8eae67fbbf77960c33c676ad9f4efc7" integrity sha512-0ilKFI6QQF5nxDZLFn2dMjvc4hjg/Wkg7rHd3jK6/A4a1Hl9VFdQWvgB1UMGoU94pad1P/8N7fMcEnLnSiju8A== dependencies: "@types/json-schema" "^7.0.4" ajv "^6.12.2" ajv-keywords "^3.4.1" schema-utils@^3.1.0, schema-utils@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-3.1.1.tgz#bc74c4b6b6995c1d88f76a8b77bea7219e0c8281" integrity sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw== dependencies: "@types/json-schema" "^7.0.8" ajv "^6.12.5" ajv-keywords "^3.5.2" semver-compare@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= "semver@2 || 3 || 4 || 5", semver@^5.6.0: version "5.7.0" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b" integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA== semver@^5.1.0, semver@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db" integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A== semver@^6.1.0, semver@^6.1.2, semver@^6.2.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== semver@^7.0.0: version "7.3.5" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7" integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== dependencies: lru-cache "^6.0.0" semver@^7.2.1, semver@^7.3.2: version "7.3.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938" integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ== semver@^7.3.5, semver@^7.3.8: version "7.3.8" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== dependencies: lru-cache "^6.0.0" [email protected]: version "0.18.0" resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be" integrity sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg== dependencies: debug "2.6.9" depd "2.0.0" destroy "1.2.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" fresh "0.5.2" http-errors "2.0.0" mime "1.6.0" ms "2.1.3" on-finished "2.4.1" range-parser "~1.2.1" statuses "2.0.1" serialize-error@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/serialize-error/-/serialize-error-7.0.1.tgz#f1360b0447f61ffb483ec4157c737fab7d778e18" integrity sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw== dependencies: type-fest "^0.13.1" serialize-javascript@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== dependencies: randombytes "^2.1.0" [email protected]: version "1.15.0" resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.15.0.tgz#faaef08cffe0a1a62f60cad0c4e513cff0ac9540" integrity sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g== dependencies: encodeurl "~1.0.2" escape-html "~1.0.3" parseurl "~1.3.3" send "0.18.0" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== shallow-clone@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== dependencies: kind-of "^6.0.2" shebang-command@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= dependencies: shebang-regex "^1.0.0" shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== dependencies: shebang-regex "^3.0.0" shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= shebang-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== shelljs@^0.8.1: version "0.8.5" resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.8.5.tgz#de055408d8361bed66c669d2f000538ced8ee20c" integrity sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow== dependencies: glob "^7.0.0" interpret "^1.0.0" rechoir "^0.6.2" shx@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/shx/-/shx-0.3.2.tgz#40501ce14eb5e0cbcac7ddbd4b325563aad8c123" integrity sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA== dependencies: es6-object-assign "^1.0.3" minimist "^1.2.0" shelljs "^0.8.1" side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== dependencies: call-bind "^1.0.0" get-intrinsic "^1.0.2" object-inspect "^1.9.0" signal-exit@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== simple-git@^3.5.0: version "3.16.0" resolved "https://registry.yarnpkg.com/simple-git/-/simple-git-3.16.0.tgz#421773e24680f5716999cc4a1d60127b4b6a9dec" integrity sha512-zuWYsOLEhbJRWVxpjdiXl6eyAyGo/KzVW+KFhhw9MqEEJttcq+32jTWSGyxTdf9e/YCohxRE+9xpWFj9FdiJNw== dependencies: "@kwsites/file-exists" "^1.1.1" "@kwsites/promise-deferred" "^1.1.1" debug "^4.3.4" slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== slice-ansi@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-2.1.0.tgz#cacd7693461a637a5788d92a7dd4fba068e81636" integrity sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ== dependencies: ansi-styles "^3.2.0" astral-regex "^1.0.0" is-fullwidth-code-point "^2.0.0" slice-ansi@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" slice-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" sliced@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/sliced/-/sliced-1.0.1.tgz#0b3a662b5d04c3177b1926bea82b03f837a2ef41" integrity sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E= source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map@^0.6.0: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== spdx-correct@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== spdx-expression-parse@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: version "3.0.4" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz#75ecd1a88de8c184ef015eafb51b5b48bfd11bb1" integrity sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA== sprintf-js@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.2.tgz#da1765262bf8c0f571749f2ad6c26300207ae673" integrity sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug== sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= standard-engine@^12.0.0: version "12.1.0" resolved "https://registry.yarnpkg.com/standard-engine/-/standard-engine-12.1.0.tgz#b13dbae583de54c06805207b991ef48a582c0e62" integrity sha512-DVJnWM1CGkag4ucFLGdiYWa5/kJURPONmMmk17p8FT5NE4UnPZB1vxWnXnRo2sPSL78pWJG8xEM+1Tu19z0deg== dependencies: deglob "^4.0.1" get-stdin "^7.0.0" minimist "^1.2.5" pkg-conf "^3.1.0" standard-markdown@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/standard-markdown/-/standard-markdown-6.0.0.tgz#bb7519a86275900eaa7a951d98937723c7010ed6" integrity sha512-9lQs4ZfGukyalFVputnN4IxfbMIAECjf+BqC4gvY8eBUvYcotYIWj4MZyMiXBkN/OJwmMi5jVSnzIexKZQqQYA== dependencies: commander "^4.1.0" globby "^11.0.0" lodash.flatten "^4.4.0" lodash.range "^3.2.0" ora "^4.0.3" standard "^14.3.1" standard@^14.3.1: version "14.3.4" resolved "https://registry.yarnpkg.com/standard/-/standard-14.3.4.tgz#748e80e8cd7b535844a85a12f337755a7e3a0f6e" integrity sha512-+lpOkFssMkljJ6eaILmqxHQ2n4csuEABmcubLTb9almFi1ElDzXb1819fjf/5ygSyePCq4kU2wMdb2fBfb9P9Q== dependencies: eslint "~6.8.0" eslint-config-standard "14.1.1" eslint-config-standard-jsx "8.1.0" eslint-plugin-import "~2.18.0" eslint-plugin-node "~10.0.0" eslint-plugin-promise "~4.2.1" eslint-plugin-react "~7.14.2" eslint-plugin-standard "~4.0.0" standard-engine "^12.0.0" [email protected]: version "2.0.1" resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== stream-chain@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/stream-chain/-/stream-chain-2.2.3.tgz#44cfa21ab673e53a3f1691b3d1665c3aceb1983b" integrity sha512-w+WgmCZ6BItPAD3/4HD1eDiDHRLhjSSyIV+F0kcmmRyz8Uv9hvQF22KyaiAUmOlmX3pJ6F95h+C191UbS8Oe/g== stream-json@^1.7.1: version "1.7.1" resolved "https://registry.yarnpkg.com/stream-json/-/stream-json-1.7.1.tgz#ec7e414c2eba456c89a4b4e5223794eabc3860c4" integrity sha512-I7g0IDqvdJXbJ279/D3ZoTx0VMhmKnEF7u38CffeWdF8bfpMPsLo+5fWnkNjO2GU/JjWaRjdH+zmH03q+XGXFw== dependencies: stream-chain "^2.2.3" [email protected]: version "0.3.1" resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== string-width@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== dependencies: emoji-regex "^7.0.1" is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" string-width@^4.1.0, string-width@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== dependencies: emoji-regex "^8.0.0" is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" string-width@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.0.0.tgz#19191f152f937b96f4ec54ba0986a5656660c5a2" integrity sha512-zwXcRmLUdiWhMPrHz6EXITuyTgcEnUqDzspTkCLhQovxywWz6NP9VHgqfVg20V/1mUg0B95AKbXxNT+ALRmqCw== dependencies: emoji-regex "^9.2.2" is-fullwidth-code-point "^4.0.0" strip-ansi "^7.0.0" string.prototype.trimend@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz#85812a6b847ac002270f5808146064c995fb6913" integrity sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string.prototype.trimstart@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz#14af6d9f34b053f7cfc89b72f8f2ee14b9039a54" integrity sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string_decoder@^1.1.1: version "1.3.0" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== dependencies: safe-buffer "~5.2.0" string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" stringify-object@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== dependencies: get-own-enumerable-property-symbols "^3.0.0" is-obj "^1.0.1" is-regexp "^1.0.0" strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== dependencies: ansi-regex "^4.1.0" strip-ansi@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== dependencies: ansi-regex "^5.0.0" strip-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.0.tgz#1dc49b980c3a4100366617adac59327eefdefcb0" integrity sha512-UhDTSnGF1dc0DRbUqr1aXwNoY3RgVkSWG8BrpnuFIxhP57IqbS7IRta2Gfiavds4yCxc5+fEAVVOgBZWnYkvzg== dependencies: ansi-regex "^6.0.0" strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= strip-final-newline@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== strip-json-comments@^3.0.1, strip-json-comments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.0.tgz#7638d31422129ecf4457440009fba03f9f9ac180" integrity sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w== strip-json-comments@~3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== sumchecker@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/sumchecker/-/sumchecker-3.0.1.tgz#6377e996795abb0b6d348e9b3e1dfb24345a8e42" integrity sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg== dependencies: debug "^4.1.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" supports-color@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.1.0.tgz#68e32591df73e25ad1c4b49108a2ec507962bfd1" integrity sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g== dependencies: has-flag "^4.0.0" supports-color@^8.0.0: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== dependencies: has-flag "^4.0.0" supports-color@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.0.2.tgz#50f082888e4b0a4e2ccd2d0b4f9ef4efcd332485" integrity sha512-ii6tc8ImGFrgMPYq7RVAMKkhPo9vk8uA+D3oKbJq/3Pk2YSMv1+9dUAesa9UxMbxBTvxwKTQffBahNVNxEvM8Q== dependencies: has-flag "^5.0.0" supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== table@^5.2.3: version "5.4.6" resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e" integrity sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug== dependencies: ajv "^6.10.2" lodash "^4.17.14" slice-ansi "^2.1.0" string-width "^3.0.0" tap-parser@~1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-1.2.2.tgz#5e2f6970611f079c7cf857de1dc7aa1b480de7a5" integrity sha1-Xi9pcGEfB5x8+FfeHceqG0gN56U= dependencies: events-to-array "^1.0.1" inherits "~2.0.1" js-yaml "^3.2.7" optionalDependencies: readable-stream "^2" tap-xunit@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/tap-xunit/-/tap-xunit-2.4.1.tgz#9823797b676ae5017f4e380bd70abb893b8e120e" integrity sha512-qcZStDtjjYjMKAo7QNiCtOW256g3tuSyCSe5kNJniG1Q2oeOExJq4vm8CwboHZURpkXAHvtqMl4TVL7mcbMVVA== dependencies: duplexer "~0.1.1" minimist "~1.2.0" tap-parser "~1.2.2" through2 "~2.0.0" xmlbuilder "~4.2.0" xtend "~4.0.0" tapable@^1.0.0: version "1.1.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== tapable@^2.1.1, tapable@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== tar@^6.1.11: version "6.1.13" resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b" integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw== dependencies: chownr "^2.0.0" fs-minipass "^2.0.0" minipass "^4.0.0" minizlib "^2.1.1" mkdirp "^1.0.3" yallist "^4.0.0" temp@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/temp/-/temp-0.8.3.tgz#e0c6bc4d26b903124410e4fed81103014dfc1f59" integrity sha1-4Ma8TSa5AxJEEOT+2BEDAU38H1k= dependencies: os-tmpdir "^1.0.0" rimraf "~2.2.6" terser-webpack-plugin@^5.1.3: version "5.3.3" resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.3.tgz#8033db876dd5875487213e87c627bca323e5ed90" integrity sha512-Fx60G5HNYknNTNQnzQ1VePRuu89ZVYWfjRAeT5rITuCY/1b08s49e5kSQwHDirKZWuoKOBRFS98EUUoZ9kLEwQ== dependencies: "@jridgewell/trace-mapping" "^0.3.7" jest-worker "^27.4.5" schema-utils "^3.1.1" serialize-javascript "^6.0.0" terser "^5.7.2" terser@^5.7.2: version "5.14.2" resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== dependencies: "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" commander "^2.20.0" source-map-support "~0.5.20" text-table@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= through2@~2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== dependencies: readable-stream "~2.3.6" xtend "~4.0.1" through@^2.3.6, through@^2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= [email protected]: version "1.4.2" resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.4.2.tgz#c9c58b575be8407375cb5e2462dacee74359f41d" integrity sha1-ycWLV1voQHN1y14kYtrO50NZ9B0= dependencies: process "~0.11.0" tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== dependencies: is-number "^7.0.0" to-vfile@^7.0.0: version "7.2.1" resolved "https://registry.yarnpkg.com/to-vfile/-/to-vfile-7.2.1.tgz#fe42892024f724177ba81076f98ee74b0888c293" integrity sha512-biljADNq2n+AZn/zX+/87zStnIqctKr/q5OaOD8+qSKINokUGPbWBShvxa1iLUgHz6dGGjVnQPNoFRtVBzMkVg== dependencies: is-buffer "^2.0.0" vfile "^5.0.0" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= trough@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/trough/-/trough-2.0.2.tgz#94a3aa9d5ce379fc561f6244905b3f36b7458d96" integrity sha512-FnHq5sTMxC0sk957wHDzRnemFnNBvt/gSY99HzK8F7UP5WAbvP70yX5bd7CjEQkN+TjdxwI7g7lJ6podqrG2/w== ts-loader@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-8.0.2.tgz#ee73ca9350f745799396fff8578ba29b1e95616b" integrity sha512-oYT7wOTUawYXQ8XIDsRhziyW0KUEV38jISYlE+9adP6tDtG+O5GkRe4QKQXrHVH4mJJ88DysvEtvGP65wMLlhg== dependencies: chalk "^2.3.0" enhanced-resolve "^4.0.0" loader-utils "^1.0.2" micromatch "^4.0.0" semver "^6.0.0" [email protected]: version "6.2.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-6.2.0.tgz#65a0ae2acce319ea4fd7ac8d7c9f1f90c5da6baf" integrity sha512-ZNT+OEGfUNVMGkpIaDJJ44Zq3Yr0bkU/ugN1PHbU+/01Z7UV1fsELRiTx1KuQNvQ1A3pGh3y25iYF6jXgxV21A== dependencies: arrify "^1.0.0" buffer-from "^1.1.0" diff "^3.1.0" make-error "^1.1.1" minimist "^1.2.0" mkdirp "^0.5.1" source-map-support "^0.5.6" yn "^2.0.0" tsconfig-paths@^3.9.0: version "3.9.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz#098547a6c4448807e8fcb8eae081064ee9a3c90b" integrity sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw== dependencies: "@types/json5" "^0.0.29" json5 "^1.0.1" minimist "^1.2.0" strip-bom "^3.0.0" tslib@^1.8.1, tslib@^1.9.0: version "1.10.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== tslib@^2.0.0, tslib@^2.2.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== dependencies: tslib "^1.8.1" tunnel@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== dependencies: prelude-ls "^1.2.1" type-check@~0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= dependencies: prelude-ls "~1.1.2" type-detect@^4.0.0, type-detect@^4.0.5: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== type-fest@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.11.0.tgz#97abf0872310fed88a5c466b25681576145e33f1" integrity sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ== type-fest@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934" integrity sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg== type-fest@^0.3.0: version "0.3.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ== type-fest@^0.8.1: version "0.8.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== type-is@~1.6.18: version "1.6.18" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== dependencies: media-typer "0.3.0" mime-types "~2.1.24" typedarray@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= typescript@^4.5.5: version "4.5.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== unified-args@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/unified-args/-/unified-args-9.0.2.tgz#0c14f555e73ee29c23f9a567942e29069f56e5a2" integrity sha512-qSqryjoqfJSII4E4Z2Jx7MhXX2MuUIn6DsrlmL8UnWFdGtrWvEtvm7Rx5fKT5TPUz7q/Fb4oxwIHLCttvAuRLQ== dependencies: "@types/text-table" "^0.2.0" camelcase "^6.0.0" chalk "^4.0.0" chokidar "^3.0.0" fault "^2.0.0" json5 "^2.0.0" minimist "^1.0.0" text-table "^0.2.0" unified-engine "^9.0.0" unified-engine@^9.0.0: version "9.0.3" resolved "https://registry.yarnpkg.com/unified-engine/-/unified-engine-9.0.3.tgz#c1d57e67d94f234296cbfa9364f43e0696dae016" integrity sha512-SgzREcCM2IpUy3JMFUcPRZQ2Py6IwvJ2KIrg2AiI7LnGge6E6OPFWpcabHrEXG0IvO2OI3afiD9DOcQvvZfXDQ== dependencies: "@types/concat-stream" "^1.0.0" "@types/debug" "^4.0.0" "@types/is-empty" "^1.0.0" "@types/js-yaml" "^4.0.0" "@types/node" "^16.0.0" "@types/unist" "^2.0.0" concat-stream "^2.0.0" debug "^4.0.0" fault "^2.0.0" glob "^7.0.0" ignore "^5.0.0" is-buffer "^2.0.0" is-empty "^1.0.0" is-plain-obj "^4.0.0" js-yaml "^4.0.0" load-plugin "^4.0.0" parse-json "^5.0.0" to-vfile "^7.0.0" trough "^2.0.0" unist-util-inspect "^7.0.0" vfile-message "^3.0.0" vfile-reporter "^7.0.0" vfile-statistics "^2.0.0" unified-lint-rule@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/unified-lint-rule/-/unified-lint-rule-1.0.4.tgz#be432d316db7ad801166041727b023ba18963e24" integrity sha512-q9wY6S+d38xRAuWQVOMjBQYi7zGyKkY23ciNafB8JFVmDroyKjtytXHCg94JnhBCXrNqpfojo3+8D+gmF4zxJQ== dependencies: wrapped "^1.0.1" unified-message-control@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unified-message-control/-/unified-message-control-3.0.3.tgz#d08c4564092a507668de71451a33c0d80e734bbd" integrity sha512-oY5z2n8ugjpNHXOmcgrw0pQeJzavHS0VjPBP21tOcm7rc2C+5Q+kW9j5+gqtf8vfW/8sabbsK5+P+9QPwwEHDA== dependencies: unist-util-visit "^2.0.0" vfile-location "^3.0.0" unified@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/unified/-/unified-10.1.0.tgz#4e65eb38fc2448b1c5ee573a472340f52b9346fe" integrity sha512-4U3ru/BRXYYhKbwXV6lU6bufLikoAavTwev89H5UxY8enDFaAT2VXmIXYNm6hb5oHPng/EXr77PVyDFcptbk5g== dependencies: "@types/unist" "^2.0.0" bail "^2.0.0" extend "^3.0.0" is-buffer "^2.0.0" is-plain-obj "^4.0.0" trough "^2.0.0" vfile "^5.0.0" uniq@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" integrity sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8= unist-util-generated@^1.0.0: version "1.1.6" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.6.tgz#5ab51f689e2992a472beb1b35f2ce7ff2f324d4b" integrity sha512-cln2Mm1/CZzN5ttGK7vkoGw+RZ8VcUH6BtGbq98DDtRGquAAOXig1mrBQYelOwMXYS8rK+vZDyyojSjp7JX+Lg== unist-util-generated@^1.1.0: version "1.1.4" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.4.tgz#2261c033d9fc23fae41872cdb7663746e972c1a7" integrity sha512-SA7Sys3h3X4AlVnxHdvN/qYdr4R38HzihoEVY2Q2BZu8NHWDnw5OGcC/tXWjQfd4iG+M6qRFNIRGqJmp2ez4Ww== unist-util-inspect@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/unist-util-inspect/-/unist-util-inspect-7.0.0.tgz#98426f0219e24d011a27e32539be0693d9eb973e" integrity sha512-2Utgv78I7PUu461Y9cdo+IUiiKSKpDV5CE/XD6vTj849a3xlpDAScvSJ6cQmtFBGgAmCn2wR7jLuXhpg1XLlJw== dependencies: "@types/unist" "^2.0.0" unist-util-is@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-4.1.0.tgz#976e5f462a7a5de73d94b706bac1b90671b57797" integrity sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg== unist-util-is@^5.0.0: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-5.1.1.tgz#e8aece0b102fa9bc097b0fef8f870c496d4a6236" integrity sha512-F5CZ68eYzuSvJjGhCLPL3cYx45IxkqXSetCcRgUXtbcm50X2L9oOWQlfUfDdAf+6Pd27YDblBfdtmsThXmwpbQ== unist-util-position@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unist-util-position/-/unist-util-position-3.0.3.tgz#fff942b879538b242096c148153826664b1ca373" integrity sha512-28EpCBYFvnMeq9y/4w6pbnFmCUfzlsc41NJui5c51hOFjBA1fejcwc+5W4z2+0ECVbScG3dURS3JTVqwenzqZw== unist-util-stringify-position@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-2.0.1.tgz#de2a2bc8d3febfa606652673a91455b6a36fb9f3" integrity sha512-Zqlf6+FRI39Bah8Q6ZnNGrEHUhwJOkHde2MHVk96lLyftfJJckaPslKgzhVcviXj8KcE9UJM9F+a4JEiBUTYgA== dependencies: "@types/unist" "^2.0.2" unist-util-stringify-position@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-3.0.0.tgz#d517d2883d74d0daa0b565adc3d10a02b4a8cde9" integrity sha512-SdfAl8fsDclywZpfMDTVDxA2V7LjtRDTOFd44wUJamgl6OlVngsqWjxvermMYf60elWHbxhuRCZml7AnuXCaSA== dependencies: "@types/unist" "^2.0.0" unist-util-visit-parents@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz#65a6ce698f78a6b0f56aa0e88f13801886cdaef6" integrity sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-5.1.1.tgz#868f353e6fce6bf8fa875b251b0f4fec3be709bb" integrity sha512-gks4baapT/kNRaWxuGkl5BIhoanZo7sC/cUT/JToSRNL1dYoXRFl75d++NkjYk4TAu2uv2Px+l8guMajogeuiw== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-2.0.3.tgz#c3703893146df47203bb8a9795af47d7b971208c" integrity sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents "^3.0.0" unist-util-visit@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.1.tgz#1c4842d70bd3df6cc545276f5164f933390a9aad" integrity sha512-n9KN3WV9k4h1DxYR1LoajgN93wpEi/7ZplVe02IoB4gH5ctI1AaF2670BLHQYbwj+pY83gFtyeySFiyMHJklrg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit-parents "^5.1.1" universal-github-app-jwt@^1.0.1: version "1.1.1" resolved "https://registry.yarnpkg.com/universal-github-app-jwt/-/universal-github-app-jwt-1.1.1.tgz#d57cee49020662a95ca750a057e758a1a7190e6e" integrity sha512-G33RTLrIBMFmlDV4u4CBF7dh71eWwykck4XgaxaIVeZKOYZRAAxvcGMRFTUclVY6xoUPQvO4Ne5wKGxYm/Yy9w== dependencies: "@types/jsonwebtoken" "^9.0.0" jsonwebtoken "^9.0.0" universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== universalify@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== universalify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d" integrity sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug== universalify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== [email protected], unpipe@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" integrity sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw= update-browserslist-db@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38" integrity sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q== dependencies: escalade "^3.1.1" picocolors "^1.0.0" uri-js@^4.2.2: version "4.4.1" resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== dependencies: punycode "^2.1.0" url@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1" integrity sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ== dependencies: punycode "1.3.2" querystring "0.2.0" util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM= uuid@^8.3.0: version "8.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== uvu@^0.5.0: version "0.5.6" resolved "https://registry.yarnpkg.com/uvu/-/uvu-0.5.6.tgz#2754ca20bcb0bb59b64e9985e84d2e81058502df" integrity sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA== dependencies: dequal "^2.0.0" diff "^5.0.0" kleur "^4.0.3" sade "^1.7.3" v8-compile-cache@^2.0.3: version "2.1.1" resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745" integrity sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ== validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" vary@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw= vfile-location@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-3.2.0.tgz#d8e41fbcbd406063669ebf6c33d56ae8721d0f3c" integrity sha512-aLEIZKv/oxuCDZ8lkJGhuhztf/BW4M+iHdCwglA/eWc+vtuRFJj8EtgceYFX4LRjOhCAAiNHsKGssC6onJ+jbA== vfile-message@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.0.1.tgz#b9bcf87cb5525e61777e0c6df07e816a577588a3" integrity sha512-gYmSHcZZUEtYpTmaWaFJwsuUD70/rTY4v09COp8TGtOkix6gGxb/a8iTQByIY9ciTk9GwAwIXd/J9OPfM4Bvaw== dependencies: "@types/unist" "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-reporter@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.1.tgz#759bfebb995f3dc8c644284cb88ac4b310ebd168" integrity sha512-pof+cQSJCUNmHG6zoBOJfErb6syIWHWM14CwKjsugCixxl4CZdrgzgxwLBW8lIB6czkzX0Agnnhj33YpKyLvmA== dependencies: "@types/repeat-string" "^1.0.0" "@types/supports-color" "^8.0.0" repeat-string "^1.0.0" string-width "^5.0.0" supports-color "^9.0.0" unist-util-stringify-position "^3.0.0" vfile-sort "^3.0.0" vfile-statistics "^2.0.0" vfile-sort@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/vfile-sort/-/vfile-sort-3.0.0.tgz#ee13d3eaac0446200a2047a3b45d78fad6b106e6" integrity sha512-fJNctnuMi3l4ikTVcKpxTbzHeCgvDhnI44amA3NVDvA6rTC6oKCFpCVyT5n2fFMr3ebfr+WVQZedOCd73rzSxg== dependencies: vfile-message "^3.0.0" vfile-statistics@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/vfile-statistics/-/vfile-statistics-2.0.0.tgz#f04ee3e3c666809a3c10c06021becd41ea9c8037" integrity sha512-foOWtcnJhKN9M2+20AOTlWi2dxNfAoeNIoxD5GXcO182UJyId4QrXa41fWrgcfV3FWTjdEDy3I4cpLVcQscIMA== dependencies: vfile-message "^3.0.0" vfile@^5.0.0: version "5.0.2" resolved "https://registry.yarnpkg.com/vfile/-/vfile-5.0.2.tgz#57773d1d91478b027632c23afab58ec3590344f0" integrity sha512-5cV+K7tX83MT3bievROc+7AvHv0GXDB0zqbrTjbOe+HRbkzvY4EP+wS3IR77kUBCoWFMdG9py18t0sesPtQ1Rw== dependencies: "@types/unist" "^2.0.0" is-buffer "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" [email protected]: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz#f239ed2cd6004021b6550af9fd9d3e47eee3cac9" integrity sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ== [email protected]: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz#beaa46aea06ed061576586c5e11368a9afc1d378" integrity sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg== dependencies: vscode-jsonrpc "8.0.2" vscode-languageserver-types "3.17.2" vscode-languageserver-textdocument@^1.0.5, vscode-languageserver-textdocument@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz#16df468d5c2606103c90554ae05f9f3d335b771b" integrity sha512-bFJH7UQxlXT8kKeyiyu41r22jCZXG8kuuVVA33OEJn1diWOZK5n8zBSPZFHVBOu8kXZ6h0LIRhf5UnCo61J4Hg== [email protected], vscode-languageserver-types@^3.17.1: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz#b2c2e7de405ad3d73a883e91989b850170ffc4f2" integrity sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA== vscode-languageserver@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.0.2.tgz#cfe2f0996d9dfd40d3854e786b2821604dfec06d" integrity sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA== dependencies: vscode-languageserver-protocol "3.17.2" vscode-uri@^3.0.3, vscode-uri@^3.0.6: version "3.0.6" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.6.tgz#5e6e2e1a4170543af30151b561a41f71db1d6f91" integrity sha512-fmL7V1eiDBFRRnu+gfRWTzyPpNIHJTc4mWnFkwBUmO9U3KPgJAmTx7oxi2bl/Rh6HLdU7+4C9wlj0k2E4AdKFQ== walk-sync@^0.3.2: version "0.3.4" resolved "https://registry.yarnpkg.com/walk-sync/-/walk-sync-0.3.4.tgz#cf78486cc567d3a96b5b2237c6108017a5ffb9a4" integrity sha512-ttGcuHA/OBnN2pcM6johpYlEms7XpO5/fyKIr48541xXedan4roO8cS1Q2S/zbbjGH/BarYDAMeS2Mi9HE5Tig== dependencies: ensure-posix-path "^1.0.0" matcher-collection "^1.0.0" watchpack@^2.4.0: version "2.4.0" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" integrity sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g= dependencies: defaults "^1.0.3" webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE= webpack-cli@^4.10.0: version "4.10.0" resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== dependencies: "@discoveryjs/json-ext" "^0.5.0" "@webpack-cli/configtest" "^1.2.0" "@webpack-cli/info" "^1.5.0" "@webpack-cli/serve" "^1.7.0" colorette "^2.0.14" commander "^7.0.0" cross-spawn "^7.0.3" fastest-levenshtein "^1.0.12" import-local "^3.0.2" interpret "^2.2.0" rechoir "^0.7.0" webpack-merge "^5.7.3" webpack-merge@^5.7.3: version "5.8.0" resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" integrity sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q== dependencies: clone-deep "^4.0.1" wildcard "^2.0.0" webpack-sources@^3.2.3: version "3.2.3" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== webpack@^5, webpack@^5.76.0: version "5.76.0" resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.76.0.tgz#f9fb9fb8c4a7dbdcd0d56a98e56b8a942ee2692c" integrity sha512-l5sOdYBDunyf72HW8dF23rFtWq/7Zgvt/9ftMof71E/yUb1YLOBmTgA2K4vQthB3kotMrSj609txVE0dnr2fjA== dependencies: "@types/eslint-scope" "^3.7.3" "@types/estree" "^0.0.51" "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/wasm-edit" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" acorn "^8.7.1" acorn-import-assertions "^1.7.6" browserslist "^4.14.5" chrome-trace-event "^1.0.2" enhanced-resolve "^5.10.0" es-module-lexer "^0.9.0" eslint-scope "5.1.1" events "^3.2.0" glob-to-regexp "^0.4.1" graceful-fs "^4.2.9" json-parse-even-better-errors "^2.3.1" loader-runner "^4.2.0" mime-types "^2.1.27" neo-async "^2.6.2" schema-utils "^3.1.0" tapable "^2.1.1" terser-webpack-plugin "^5.1.3" watchpack "^2.4.0" webpack-sources "^3.2.3" whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" integrity sha1-lmRU6HZUYuN2RNNib2dCzotwll0= dependencies: tr46 "~0.0.3" webidl-conversions "^3.0.0" which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" which@^2.0.1: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" wildcard@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== word-wrap@^1.2.3, word-wrap@~1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== wrap-ansi@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== dependencies: ansi-styles "^4.0.0" string-width "^4.1.0" strip-ansi "^6.0.0" wrapped@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wrapped/-/wrapped-1.0.1.tgz#c783d9d807b273e9b01e851680a938c87c907242" integrity sha1-x4PZ2Aeyc+mwHoUWgKk4yHyQckI= dependencies: co "3.1.0" sliced "^1.0.1" wrapper-webpack-plugin@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/wrapper-webpack-plugin/-/wrapper-webpack-plugin-2.2.2.tgz#a950b7fbc39ca103e468a7c06c225cb1e337ad3b" integrity sha512-twLGZw0b2AEnz3LmsM/uCFRzGxE+XUlUPlJkCuHY3sI+uGO4dTJsgYee3ufWJaynAZYkpgQSKMSr49n9Yxalzg== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= [email protected]: version "1.0.3" resolved "https://registry.yarnpkg.com/write/-/write-1.0.3.tgz#0800e14523b923a387e415123c865616aae0f5c3" integrity sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig== dependencies: mkdirp "^0.5.1" xml2js@^0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.5.0.tgz#d9440631fbb2ed800203fad106f2724f62c493b7" integrity sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA== dependencies: sax ">=0.6.0" xmlbuilder "~11.0.0" xmlbuilder@~11.0.0: version "11.0.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== xmlbuilder@~4.2.0: version "4.2.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5" integrity sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU= dependencies: lodash "^4.0.0" xtend@^4.0.1, xtend@~4.0.0, xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== yallist@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== yaml@^1.7.2: version "1.10.0" resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9" integrity sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g== dependencies: buffer-crc32 "~0.2.3" fd-slicer "~1.1.0" yn@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/yn/-/yn-2.0.0.tgz#e5adabc8acf408f6385fc76495684c88e6af689a" integrity sha1-5a2ryKz0CPY4X8dklWhMiOavaJo= zwitch@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.2.tgz#91f8d0e901ffa3d66599756dde7f57b17c95dce1" integrity sha512-JZxotl7SxAJH0j7dN4pxsTV6ZLXoLdGME+PsjkL/DaBrVryK9kTGq06GfKrwcSOqypP+fdXGoCHE36b99fWVoA==
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
.markdownlint.json
{ "commands-show-output": false, "first-line-h1": false, "header-increment": false, "line-length": { "code_blocks": false, "tables": false, "stern": true, "line_length": -1 }, "no-bare-urls": false, "no-blanks-blockquote": false, "no-duplicate-header": { "allow_different_nesting": true }, "no-emphasis-as-header": false, "no-hard-tabs": { "code_blocks": false }, "no-space-in-emphasis": false, "no-trailing-punctuation": false, "no-trailing-spaces": { "br_spaces": 0 }, "single-h1": false, "no-inline-html": false }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
package.json
{ "name": "electron", "version": "0.0.0-development", "repository": "https://github.com/electron/electron", "description": "Build cross platform desktop apps with JavaScript, HTML, and CSS", "devDependencies": { "@azure/storage-blob": "^12.9.0", "@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4", "@electron/asar": "^3.2.1", "@electron/docs-parser": "^1.1.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^1.5.0", "@electron/typescript-definitions": "^8.14.0", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", "@types/basic-auth": "^1.1.3", "@types/busboy": "^1.5.0", "@types/chai": "^4.2.12", "@types/chai-as-promised": "^7.1.3", "@types/dirty-chai": "^2.0.2", "@types/express": "^4.17.13", "@types/fs-extra": "^9.0.1", "@types/klaw": "^3.0.1", "@types/minimist": "^1.2.0", "@types/mocha": "^7.0.2", "@types/node": "^18.11.18", "@types/semver": "^7.3.3", "@types/send": "^0.14.5", "@types/split": "^1.0.0", "@types/stream-json": "^1.5.1", "@types/temp": "^0.8.34", "@types/uuid": "^3.4.6", "@types/webpack": "^5.28.0", "@types/webpack-env": "^1.17.0", "@typescript-eslint/eslint-plugin": "^4.4.1", "@typescript-eslint/parser": "^4.4.1", "buffer": "^6.0.3", "check-for-leaks": "^1.2.1", "colors": "1.4.0", "dotenv-safe": "^4.0.4", "dugite": "^2.3.0", "eslint": "^7.4.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.22.0", "eslint-plugin-mocha": "^7.0.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-standard": "^4.0.1", "eslint-plugin-typescript": "^0.14.0", "events": "^3.2.0", "express": "^4.16.4", "folder-hash": "^2.1.1", "fs-extra": "^9.0.1", "got": "^11.8.5", "husky": "^8.0.1", "klaw": "^3.0.0", "lint": "^1.1.2", "lint-staged": "^10.2.11", "markdownlint-cli": "^0.33.0", "mdast-util-from-markdown": "^1.2.0", "minimist": "^1.2.6", "null-loader": "^4.0.0", "pre-flight": "^1.1.0", "process": "^0.11.10", "remark-cli": "^10.0.0", "remark-preset-lint-markdown-style-guide": "^4.0.0", "semver": "^5.6.0", "shx": "^0.3.2", "standard-markdown": "^6.0.0", "stream-json": "^1.7.1", "tap-xunit": "^2.4.1", "temp": "^0.8.3", "timers-browserify": "1.4.2", "ts-loader": "^8.0.2", "ts-node": "6.2.0", "typescript": "^4.5.5", "unist-util-visit": "^4.1.1", "url": "^0.11.0", "vscode-languageserver": "^8.0.2", "vscode-languageserver-textdocument": "^1.0.7", "vscode-uri": "^3.0.6", "webpack": "^5.76.0", "webpack-cli": "^4.10.0", "wrapper-webpack-plugin": "^2.2.0" }, "private": true, "scripts": { "asar": "asar", "generate-version-json": "node script/generate-version-json.js", "lint": "node ./script/lint.js && npm run lint:docs", "lint:js": "node ./script/lint.js --js", "lint:clang-format": "python3 script/run-clang-format.py -r -c shell/ || (echo \"\\nCode not formatted correctly.\" && exit 1)", "lint:clang-tidy": "ts-node ./script/run-clang-tidy.ts", "lint:cpp": "node ./script/lint.js --cc", "lint:objc": "node ./script/lint.js --objc", "lint:py": "node ./script/lint.js --py", "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-fiddles && npm run lint:docs-relative-links && npm run lint:markdownlint", "lint:docs-fiddles": "standard \"docs/fiddles/**/*.js\"", "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs", "create-api-json": "node script/create-api-json.js", "create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js", "gn-typescript-definitions": "npm run create-typescript-definitions && shx cp electron.d.ts", "pre-flight": "pre-flight", "gn-check": "node ./script/gn-check.js", "gn-format": "python3 script/run-gn-format.py", "precommit": "lint-staged", "preinstall": "node -e 'process.exit(0)'", "prepack": "check-for-leaks", "prepare": "husky install", "pretest": "npm run create-typescript-definitions", "repl": "node ./script/start.js --interactive", "start": "node ./script/start.js", "test": "node ./script/spec-runner.js", "tsc": "tsc", "webpack": "webpack" }, "license": "MIT", "author": "Electron Community", "keywords": [ "electron" ], "lint-staged": { "*.{js,ts}": [ "node script/lint.js --js --fix --only --" ], "*.{js,ts,d.ts}": [ "ts-node script/gen-filenames.ts" ], "*.{cc,mm,c,h}": [ "python3 script/run-clang-format.py -r -c --fix" ], "*.md": [ "npm run lint:docs" ], "*.{gn,gni}": [ "npm run gn-check", "npm run gn-format" ], "*.py": [ "node script/lint.js --py --fix --only --" ], "docs/api/**/*.md": [ "ts-node script/gen-filenames.ts", "markdownlint --config .markdownlint.autofix.json --fix", "git add filenames.auto.gni" ], "{*.patch,.patches}": [ "node script/lint.js --patches --only --", "ts-node script/check-patch-diff.ts" ], "DEPS": [ "node script/gen-hunspell-filenames.js", "node script/gen-libc++-filenames.js" ] }, "resolutions": { "nan": "nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac" } }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/lib/markdown.ts
import * as fs from 'fs'; import * as path from 'path'; import * as MarkdownIt from 'markdown-it'; import { githubSlugifier, resolveInternalDocumentLink, ExternalHref, FileStat, HrefKind, InternalHref, IMdLinkComputer, IMdParser, ITextDocument, IWorkspace, MdLink, MdLinkKind } from '@dsanders11/vscode-markdown-languageservice'; import { Emitter, Range } from 'vscode-languageserver'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { URI } from 'vscode-uri'; import { findMatchingFiles } from './utils'; import type { Definition, ImageReference, Link, LinkReference } from 'mdast'; import type { fromMarkdown as FromMarkdownFunction } from 'mdast-util-from-markdown'; import type { Node, Position } from 'unist'; import type { visit as VisitFunction } from 'unist-util-visit'; // Helper function to work around import issues with ESM modules and ts-node // eslint-disable-next-line no-new-func const dynamicImport = new Function('specifier', 'return import(specifier)'); // Helper function from `vscode-markdown-languageservice` codebase function tryDecodeUri (str: string): string { try { return decodeURI(str); } catch { return str; } } // Helper function from `vscode-markdown-languageservice` codebase function createHref ( sourceDocUri: URI, link: string, workspace: IWorkspace ): ExternalHref | InternalHref | undefined { if (/^[a-z-][a-z-]+:/i.test(link)) { // Looks like a uri return { kind: HrefKind.External, uri: URI.parse(tryDecodeUri(link)) }; } const resolved = resolveInternalDocumentLink(sourceDocUri, link, workspace); if (!resolved) { return undefined; } return { kind: HrefKind.Internal, path: resolved.resource, fragment: resolved.linkFragment }; } function positionToRange (position: Position): Range { return { start: { character: position.start.column - 1, line: position.start.line - 1 }, end: { character: position.end.column - 1, line: position.end.line - 1 } }; } const mdIt = MarkdownIt({ html: true }); export class MarkdownParser implements IMdParser { slugifier = githubSlugifier; async tokenize (document: TextDocument) { return mdIt.parse(document.getText(), {}); } } export class DocsWorkspace implements IWorkspace { private readonly documentCache: Map<string, TextDocument>; readonly root: string; constructor (root: string) { this.documentCache = new Map(); this.root = root; } get workspaceFolders () { return [URI.file(this.root)]; } async getAllMarkdownDocuments (): Promise<Iterable<ITextDocument>> { const files = await findMatchingFiles(this.root, (file) => file.endsWith('.md') ); for (const file of files) { const document = TextDocument.create( URI.file(file).toString(), 'markdown', 1, fs.readFileSync(file, 'utf8') ); this.documentCache.set(file, document); } return this.documentCache.values(); } hasMarkdownDocument (resource: URI) { const relativePath = path.relative(this.root, resource.path); return ( !relativePath.startsWith('..') && !path.isAbsolute(relativePath) && fs.existsSync(resource.path) ); } async openMarkdownDocument (resource: URI) { if (!this.documentCache.has(resource.path)) { const document = TextDocument.create( resource.toString(), 'markdown', 1, fs.readFileSync(resource.path, 'utf8') ); this.documentCache.set(resource.path, document); } return this.documentCache.get(resource.path); } async stat (resource: URI): Promise<FileStat | undefined> { if (this.hasMarkdownDocument(resource)) { const stats = fs.statSync(resource.path); return { isDirectory: stats.isDirectory() }; } return undefined; } async readDirectory (): Promise<Iterable<readonly [string, FileStat]>> { throw new Error('Not implemented'); } // // These events are defined to fulfill the interface, but are never emitted // by this implementation since it's not meant for watching a workspace // #onDidChangeMarkdownDocument = new Emitter<ITextDocument>(); onDidChangeMarkdownDocument = this.#onDidChangeMarkdownDocument.event; #onDidCreateMarkdownDocument = new Emitter<ITextDocument>(); onDidCreateMarkdownDocument = this.#onDidCreateMarkdownDocument.event; #onDidDeleteMarkdownDocument = new Emitter<URI>(); onDidDeleteMarkdownDocument = this.#onDidDeleteMarkdownDocument.event; } export class MarkdownLinkComputer implements IMdLinkComputer { private readonly workspace: IWorkspace; constructor (workspace: IWorkspace) { this.workspace = workspace; } async getAllLinks (document: ITextDocument): Promise<MdLink[]> { const { fromMarkdown } = (await dynamicImport( 'mdast-util-from-markdown' )) as { fromMarkdown: typeof FromMarkdownFunction }; const tree = fromMarkdown(document.getText()); const links = [ ...(await this.#getInlineLinks(document, tree)), ...(await this.#getReferenceLinks(document, tree)), ...(await this.#getLinkDefinitions(document, tree)) ]; return links; } async #getInlineLinks ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const documentUri = URI.parse(document.uri); const links: MdLink[] = []; visit( tree, (node) => node.type === 'link', (node: Node) => { const link = node as Link; const href = createHref(documentUri, link.url, this.workspace); if (href) { const range = positionToRange(link.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; const fragmentRange = undefined; links.push({ kind: MdLinkKind.Link, href, source: { hrefText: link.url, resource: documentUri, range, targetRange, hrefRange, fragmentRange, pathText: link.url.split('#')[0] } }); } } ); return links; } async #getReferenceLinks ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const links: MdLink[] = []; visit( tree, (node) => ['imageReference', 'linkReference'].includes(node.type), (node: Node) => { const link = node as ImageReference | LinkReference; const range = positionToRange(link.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; links.push({ kind: MdLinkKind.Link, href: { kind: HrefKind.Reference, ref: link.label! }, source: { hrefText: link.label!, resource: URI.parse(document.uri), range, targetRange, hrefRange, fragmentRange: undefined, pathText: link.label! } }); } ); return links; } async #getLinkDefinitions ( document: ITextDocument, tree: Node ): Promise<MdLink[]> { const { visit } = (await dynamicImport('unist-util-visit')) as { visit: typeof VisitFunction; }; const documentUri = URI.parse(document.uri); const links: MdLink[] = []; visit( tree, (node) => node.type === 'definition', (node: Node) => { const definition = node as Definition; const href = createHref(documentUri, definition.url, this.workspace); if (href) { const range = positionToRange(definition.position!); // NOTE - These haven't been implemented properly, but their // values aren't used for the link linting use-case const targetRange = range; const hrefRange = range; const fragmentRange = undefined; links.push({ kind: MdLinkKind.Definition, href, ref: { range, text: definition.label! }, source: { hrefText: definition.url, resource: documentUri, range, targetRange, hrefRange, fragmentRange, pathText: definition.url.split('#')[0] } }); } } ); return links; } }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/lint-docs-links.ts
#!/usr/bin/env ts-node import * as path from 'path'; import { createLanguageService, DiagnosticLevel, DiagnosticOptions, ILogger } from '@dsanders11/vscode-markdown-languageservice'; import * as minimist from 'minimist'; import fetch from 'node-fetch'; import { CancellationTokenSource } from 'vscode-languageserver'; import { URI } from 'vscode-uri'; import { DocsWorkspace, MarkdownLinkComputer, MarkdownParser } from './lib/markdown'; class NoOpLogger implements ILogger { log (): void {} } const diagnosticOptions: DiagnosticOptions = { ignoreLinks: [], validateDuplicateLinkDefinitions: DiagnosticLevel.error, validateFileLinks: DiagnosticLevel.error, validateFragmentLinks: DiagnosticLevel.error, validateMarkdownFileLinkFragments: DiagnosticLevel.error, validateReferences: DiagnosticLevel.error, validateUnusedLinkDefinitions: DiagnosticLevel.error }; async function fetchExternalLink (link: string, checkRedirects = false) { try { const response = await fetch(link); if (response.status !== 200) { console.log('Broken link', link, response.status, response.statusText); } else { if (checkRedirects && response.redirected) { const wwwUrl = new URL(link); wwwUrl.hostname = `www.${wwwUrl.hostname}`; // For now cut down on noise to find meaningful redirects const wwwRedirect = wwwUrl.toString() === response.url; const trailingSlashRedirect = `${link}/` === response.url; if (!wwwRedirect && !trailingSlashRedirect) { console.log('Link redirection', link, '->', response.url); } } return true; } } catch { console.log('Broken link', link); } return false; } async function main ({ fetchExternalLinks = false, checkRedirects = false }) { const workspace = new DocsWorkspace(path.resolve(__dirname, '..', 'docs')); const parser = new MarkdownParser(); const linkComputer = new MarkdownLinkComputer(workspace); const languageService = createLanguageService({ workspace, parser, logger: new NoOpLogger(), linkComputer }); const cts = new CancellationTokenSource(); let errors = false; const externalLinks = new Set<string>(); try { // Collect diagnostics for all documents in the workspace for (const document of await workspace.getAllMarkdownDocuments()) { for (let link of await languageService.getDocumentLinks( document, cts.token )) { if (link.target === undefined) { link = (await languageService.resolveDocumentLink(link, cts.token)) ?? link; } if ( link.target && link.target.startsWith('http') && new URL(link.target).hostname !== 'localhost' ) { externalLinks.add(link.target); } } const diagnostics = await languageService.computeDiagnostics( document, diagnosticOptions, cts.token ); if (diagnostics.length) { console.log( 'File Location:', path.relative(workspace.root, URI.parse(document.uri).path) ); } for (const diagnostic of diagnostics) { console.log( `\tBroken link on line ${diagnostic.range.start.line + 1}:`, diagnostic.message ); errors = true; } } } finally { cts.dispose(); } if (fetchExternalLinks) { const externalLinkStates = await Promise.all( Array.from(externalLinks).map((link) => fetchExternalLink(link, checkRedirects) ) ); errors = errors || !externalLinkStates.every((x) => x); } return errors; } function parseCommandLine () { const showUsage = (arg?: string): boolean => { if (!arg || arg.startsWith('-')) { console.log( 'Usage: script/lint-docs-links.ts [-h|--help] [--fetch-external-links] ' + '[--check-redirects]' ); process.exit(0); } return true; }; const opts = minimist(process.argv.slice(2), { boolean: ['help', 'fetch-external-links', 'check-redirects'], stopEarly: true, unknown: showUsage }); if (opts.help) showUsage(); return opts; } if (process.mainModule === module) { const opts = parseCommandLine(); main({ fetchExternalLinks: opts['fetch-external-links'], checkRedirects: opts['check-redirects'] }) .then((errors) => { if (errors) process.exit(1); }) .catch((error) => { console.error(error); process.exit(1); }); }
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
script/markdownlint-emd001.js
const { addError, getLineMetadata, getReferenceLinkImageData } = require('markdownlint/helpers'); module.exports = { names: ['EMD001', 'no-shortcut-reference-links'], description: 'Disallow shortcut reference links (those with no link label)', tags: ['images', 'links'], function: function EMD001 (params, onError) { const lineMetadata = getLineMetadata(params); const { shortcuts } = getReferenceLinkImageData(lineMetadata); for (const [shortcut, occurrences] of shortcuts) { for (const [lineNumber] of occurrences) { addError( onError, lineNumber + 1, // human-friendly line numbers (1-based) `Disallowed shortcut reference link: "${shortcut}"` ); } } } };
closed
electron/electron
https://github.com/electron/electron
38,024
`lint:js-in-markdown` Silently Failing
`standard-markdown` won't find JS code blocks in Markdown if they have anything after the language name, and in the docs we use ` ```js title='main.js (Main Process)' ` to add metadata to the code blocks for the website.
https://github.com/electron/electron/issues/38024
https://github.com/electron/electron/pull/38191
911900eae94622e6526c95ca36c66a57e8bebbb9
9ccf2275d2e021c44f51cc3719679e927fee10fa
2023-04-19T04:55:34Z
c++
2023-05-08T10:50:42Z
yarn.lock
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@azure/abort-controller@^1.0.0": version "1.0.4" resolved "https://registry.yarnpkg.com/@azure/abort-controller/-/abort-controller-1.0.4.tgz#fd3c4d46c8ed67aace42498c8e2270960250eafd" integrity sha512-lNUmDRVGpanCsiUN3NWxFTdwmdFI53xwhkTFfHDGTYk46ca7Ind3nanJc+U6Zj9Tv+9nTCWRBscWEW1DyKOpTw== dependencies: tslib "^2.0.0" "@azure/core-asynciterator-polyfill@^1.0.0": version "1.0.2" resolved "https://registry.yarnpkg.com/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.2.tgz#0dd3849fb8d97f062a39db0e5cadc9ffaf861fec" integrity sha512-3rkP4LnnlWawl0LZptJOdXNrT/fHp2eQMadoasa6afspXdpGrtPZuAQc2PD0cpgyuoXtUWyC3tv7xfntjGS5Dw== "@azure/core-auth@^1.3.0": version "1.3.2" resolved "https://registry.yarnpkg.com/@azure/core-auth/-/core-auth-1.3.2.tgz#6a2c248576c26df365f6c7881ca04b7f6d08e3d0" integrity sha512-7CU6DmCHIZp5ZPiZ9r3J17lTKMmYsm/zGvNkjArQwPkrLlZ1TZ+EUYfGgh2X31OLMVAQCTJZW4cXHJi02EbJnA== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/core-http@^3.0.0": version "3.0.1" resolved "https://registry.yarnpkg.com/@azure/core-http/-/core-http-3.0.1.tgz#2177f3abb64afa8ca101dc34f67cc789888f9f7b" integrity sha512-A3x+um3cAPgQe42Lu7Iv/x8/fNjhL/nIoEfqFxfn30EyxK6zC13n+OUxzZBRC0IzQqssqIbt4INf5YG7lYYFtw== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-auth" "^1.3.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/core-util" "^1.1.1" "@azure/logger" "^1.0.0" "@types/node-fetch" "^2.5.0" "@types/tunnel" "^0.0.3" form-data "^4.0.0" node-fetch "^2.6.7" process "^0.11.10" tslib "^2.2.0" tunnel "^0.0.6" uuid "^8.3.0" xml2js "^0.5.0" "@azure/core-lro@^2.2.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-lro/-/core-lro-2.2.4.tgz#42fbf4ae98093c59005206a4437ddcd057c57ca1" integrity sha512-e1I2v2CZM0mQo8+RSix0x091Av493e4bnT22ds2fcQGslTHzM2oTbswkB65nP4iEpCxBrFxOSDPKExmTmjCVtQ== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" tslib "^2.2.0" "@azure/core-paging@^1.1.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@azure/core-paging/-/core-paging-1.2.1.tgz#1b884f563b6e49971e9a922da3c7a20931867b54" integrity sha512-UtH5iMlYsvg+nQYIl4UHlvvSrsBjOlRF4fs0j7mxd3rWdAStrKYrh2durOpHs5C9yZbVhsVDaisoyaf/lL1EVA== dependencies: "@azure/core-asynciterator-polyfill" "^1.0.0" tslib "^2.2.0" "@azure/[email protected]": version "1.0.0-preview.13" resolved "https://registry.yarnpkg.com/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz#55883d40ae2042f6f1e12b17dd0c0d34c536d644" integrity sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ== dependencies: "@opentelemetry/api" "^1.0.1" tslib "^2.2.0" "@azure/core-util@^1.1.1": version "1.3.1" resolved "https://registry.yarnpkg.com/@azure/core-util/-/core-util-1.3.1.tgz#e830b99231e2091a2dc9ed652fff1cda69ba6582" integrity sha512-pjfOUAb+MPLODhGuXot/Hy8wUgPD0UTqYkY3BiYcwEETrLcUCVM1t0roIvlQMgvn1lc48TGy5bsonsFpF862Jw== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/logger@^1.0.0": version "1.0.3" resolved "https://registry.yarnpkg.com/@azure/logger/-/logger-1.0.3.tgz#6e36704aa51be7d4a1bae24731ea580836293c96" integrity sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g== dependencies: tslib "^2.2.0" "@azure/storage-blob@^12.9.0": version "12.14.0" resolved "https://registry.yarnpkg.com/@azure/storage-blob/-/storage-blob-12.14.0.tgz#32d3e5fa3bb2a12d5d44b186aed11c8e78f00178" integrity sha512-g8GNUDpMisGXzBeD+sKphhH5yLwesB4JkHr1U6be/X3F+cAMcyGLPD1P89g2M7wbEtUJWoikry1rlr83nNRBzg== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-http" "^3.0.0" "@azure/core-lro" "^2.2.0" "@azure/core-paging" "^1.1.1" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" events "^3.0.0" tslib "^2.2.0" "@babel/code-frame@^7.0.0": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw== dependencies: "@babel/highlight" "^7.0.0" "@babel/highlight@^7.0.0": version "7.5.0" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540" integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ== dependencies: chalk "^2.0.0" esutils "^2.0.2" js-tokens "^4.0.0" "@discoveryjs/json-ext@^0.5.0": version "0.5.7" resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== "@dsanders11/vscode-markdown-languageservice@^0.3.0-alpha.4": version "0.3.0-alpha.4" resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0-alpha.4.tgz#cd80b82142a2c10e09b5f36a93c3ea65b7d2a7f9" integrity sha512-MHp/CniEkzJb1CAw/bHwucuImaICrcIuohEFamTW8sJC2jhKCnbYblwJFZ3OOS3wTYZbzFIa8WZ4Dn5yL2E7jg== dependencies: "@vscode/l10n" "^0.0.10" picomatch "^2.3.1" vscode-languageserver-textdocument "^1.0.5" vscode-languageserver-types "^3.17.1" vscode-uri "^3.0.3" "@electron/asar@^3.2.1": version "3.2.1" resolved "https://registry.yarnpkg.com/@electron/asar/-/asar-3.2.1.tgz#c4143896f3dd43b59a80a9c9068d76f77efb62ea" integrity sha512-hE2cQMZ5+4o7+6T2lUaVbxIzrOjZZfX7dB02xuapyYFJZEAiWTelq6J3mMoxzd0iONDvYLPVKecB5tyjIoVDVA== dependencies: chromium-pickle-js "^0.2.0" commander "^5.0.0" glob "^7.1.6" minimatch "^3.0.4" optionalDependencies: "@types/glob" "^7.1.1" "@electron/docs-parser@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.1.0.tgz#ba095def41746bde56bee731feaf22272bf0b765" integrity sha512-qrjIKJk8t4/xAYldDVNQgcF8zdAAuG260bzPxdh/xI3p/yddm61bftoct+Tx2crnWFnOfOkr6nGERsDknNiT8A== dependencies: "@types/markdown-it" "^12.0.0" chai "^4.2.0" chalk "^3.0.0" fs-extra "^8.1.0" lodash.camelcase "^4.3.0" markdown-it "^12.0.0" minimist "^1.2.0" ora "^4.0.3" pretty-ms "^5.1.0" "@electron/fiddle-core@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@electron/fiddle-core/-/fiddle-core-1.0.4.tgz#d28e330c4d88f3916269558a43d214c4312333af" integrity sha512-gjPz3IAHK+/f0N52cWVeTZpdgENJo3QHBGeGqMDHFUgzSBRTVyAr8z8Lw8wpu6Ocizs154Rtssn4ba1ysABgLA== dependencies: "@electron/get" "^2.0.0" debug "^4.3.3" env-paths "^2.2.1" extract-zip "^2.0.1" fs-extra "^10.0.0" getos "^3.2.1" node-fetch "^2.6.1" semver "^7.3.5" simple-git "^3.5.0" "@electron/get@^2.0.0": version "2.0.2" resolved "https://registry.yarnpkg.com/@electron/get/-/get-2.0.2.tgz#ae2a967b22075e9c25aaf00d5941cd79c21efd7e" integrity sha512-eFZVFoRXb3GFGd7Ak7W4+6jBl9wBtiZ4AaYOse97ej6mKj5tkyO0dUnUChs1IhJZtx1BENo4/p4WUTXpi6vT+g== dependencies: debug "^4.1.1" env-paths "^2.2.0" fs-extra "^8.1.0" got "^11.8.5" progress "^2.0.3" semver "^6.2.0" sumchecker "^3.0.1" optionalDependencies: global-agent "^3.0.0" "@electron/github-app-auth@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@electron/github-app-auth/-/github-app-auth-1.5.0.tgz#426e64ba50143417d9b68f2795a1b119cb62108b" integrity sha512-t6Za+3E7jdIf1CX06nNV/avZhqSXNEkCLJ1xeAt5FKU9HdGbjzwSfirM+UlHO7lMGyuf13BGCZOCB1kODhDLWQ== dependencies: "@octokit/auth-app" "^3.6.1" "@octokit/rest" "^18.12.0" "@electron/typescript-definitions@^8.14.0": version "8.14.0" resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.14.0.tgz#a88f74e915317ba943b57ffe499b319d04f01ee3" integrity sha512-J3b4is6L0NB4+r+7s1Hl1YlzaveKnQt1gswadRyMRwb4gFU3VAe2oBMJLOhFRJMs/9PK/Xp+y9QwyC92Tyqe6A== dependencies: "@types/node" "^11.13.7" chalk "^2.4.2" colors "^1.1.2" debug "^4.1.1" fs-extra "^7.0.1" lodash "^4.17.11" minimist "^1.2.0" mkdirp "^0.5.1" ora "^3.4.0" pretty-ms "^5.0.0" "@jridgewell/gen-mapping@^0.3.0": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== dependencies: "@jridgewell/set-array" "^1.0.1" "@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/resolve-uri@^3.0.3": version "3.1.0" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== "@jridgewell/source-map@^0.3.2": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== dependencies: "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== "@jridgewell/trace-mapping@^0.3.7", "@jridgewell/trace-mapping@^0.3.9": version "0.3.14" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz#b231a081d8f66796e475ad588a1ef473112701ed" integrity sha512-bJWEfQ9lPTvm3SneWwRFVLzrh6nhjwqw7TUFFBEMzwvg7t7PCDenf2lDwqo4NQXzdpgBXyFgDWnQA+2vkruksQ== dependencies: "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" "@kwsites/file-exists@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/file-exists/-/file-exists-1.1.1.tgz#ad1efcac13e1987d8dbaf235ef3be5b0d96faa99" integrity sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw== dependencies: debug "^4.1.1" "@kwsites/promise-deferred@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz#8ace5259254426ccef57f3175bc64ed7095ed919" integrity sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw== "@nodelib/[email protected]": version "2.1.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b" integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw== dependencies: "@nodelib/fs.stat" "2.0.3" run-parallel "^1.1.9" "@nodelib/[email protected]", "@nodelib/fs.stat@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3" integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA== "@nodelib/fs.walk@^1.2.3": version "1.2.4" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976" integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ== dependencies: "@nodelib/fs.scandir" "2.1.3" fastq "^1.6.0" "@octokit/auth-app@^3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@octokit/auth-app/-/auth-app-3.6.1.tgz#aa5b02cc211175cbc28ce6c03c73373c1206d632" integrity sha512-6oa6CFphIYI7NxxHrdVOzhG7hkcKyGyYocg7lNDSJVauVOLtylg8hNJzoUyPAYKKK0yUeoZamE/lMs2tG+S+JA== dependencies: "@octokit/auth-oauth-app" "^4.3.0" "@octokit/auth-oauth-user" "^1.2.3" "@octokit/request" "^5.6.0" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.0.3" "@types/lru-cache" "^5.1.0" deprecation "^2.3.1" lru-cache "^6.0.0" universal-github-app-jwt "^1.0.1" universal-user-agent "^6.0.0" "@octokit/auth-oauth-app@^4.3.0": version "4.3.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-app/-/auth-oauth-app-4.3.4.tgz#7030955b1a59d4d977904775c606477d95fcfe8e" integrity sha512-OYOTSSINeUAiLMk1uelaGB/dEkReBqHHr8+hBejzMG4z1vA4c7QSvDAS0RVZSr4oD4PEUPYFzEl34K7uNrXcWA== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/auth-oauth-user" "^2.0.0" "@octokit/request" "^5.6.3" "@octokit/types" "^6.0.3" "@types/btoa-lite" "^1.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^3.1.1": version "3.1.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-3.1.4.tgz#703c42f27a1e2eb23498a7001ad8e9ecf4a2f477" integrity sha512-6sHE/++r+aEFZ/BKXOGPJcH/nbgbBjS1A4CHfq/PbPEwb0kZEt43ykW98GBO/rYBPAYaNpCPvXfGwzgR9yMCXg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^6.10.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^4.0.0": version "4.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.3.tgz#00ce77233517e0d7d39e42a02652f64337d9df81" integrity sha512-KPTx5nMntKjNZzzltO3X4T68v22rd7Cp/TcLJXQE2U8aXPcZ9LFuww9q9Q5WUNSu3jwi3lRwzfkPguRfz1R8Vg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^1.2.3": version "1.3.0" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-1.3.0.tgz#da4e4529145181a6aa717ae858afb76ebd6e3360" integrity sha512-3QC/TAdk7onnxfyZ24BnJRfZv8TRzQK7SEFUS9vLng4Vv6Hv6I64ujdk/CUkREec8lhrwU764SZ/d+yrjjqhaQ== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/oauth-methods" "^1.1.0" "@octokit/request" "^5.4.14" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-2.0.4.tgz#88f060ec678d7d493695af8d827e115dd064e212" integrity sha512-HrbDzTPqz6GcGSOUkR+wSeF3vEqsb9NMsmPja/qqqdiGmlk/Czkxctc3KeWYogHonp62Ml4kjz2VxKawrFsadQ== dependencies: "@octokit/auth-oauth-device" "^4.0.0" "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-token@^2.4.4": version "2.5.0" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36" integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g== dependencies: "@octokit/types" "^6.0.3" "@octokit/auth-token@^3.0.0": version "3.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-3.0.3.tgz#ce7e48a3166731f26068d7a7a7996b5da58cbe0c" integrity sha512-/aFM2M4HVDBT/jjDBa84sJniv1t9Gm/rLkalaz9htOm+L+8JMj1k9w0CkUdcxNyNxZPlTxKPVko+m1VlM58ZVA== dependencies: "@octokit/types" "^9.0.0" "@octokit/core@^3.5.1": version "3.6.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.6.0.tgz#3376cb9f3008d9b3d110370d90e0a1fcd5fe6085" integrity sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q== dependencies: "@octokit/auth-token" "^2.4.4" "@octokit/graphql" "^4.5.8" "@octokit/request" "^5.6.3" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.0.3" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/core@^4.1.0": version "4.2.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-4.2.0.tgz#8c253ba9605aca605bc46187c34fcccae6a96648" integrity sha512-AgvDRUg3COpR82P7PBdGZF/NNqGmtMq2NiPqeSsDIeCfYFOZ9gddqWNQHnFdEUf+YwOj4aZYmJnlPp7OXmDIDg== dependencies: "@octokit/auth-token" "^3.0.0" "@octokit/graphql" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^9.0.0" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^6.0.1": version "6.0.5" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.5.tgz#43a6adee813c5ffd2f719e20cfd14a1fee7c193a" integrity sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ== dependencies: "@octokit/types" "^5.0.0" is-plain-object "^4.0.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^7.0.0": version "7.0.3" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-7.0.3.tgz#0b96035673a9e3bedf8bab8f7335de424a2147ed" integrity sha512-57gRlb28bwTsdNXq+O3JTQ7ERmBTuik9+LelgcLIVfYwf235VHbN9QNo4kXExtp/h8T423cR5iJThKtFYxC7Lw== dependencies: "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" universal-user-agent "^6.0.0" "@octokit/graphql@^4.5.8": version "4.8.0" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3" integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg== dependencies: "@octokit/request" "^5.6.0" "@octokit/types" "^6.0.3" universal-user-agent "^6.0.0" "@octokit/graphql@^5.0.0": version "5.0.5" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-5.0.5.tgz#a4cb3ea73f83b861893a6370ee82abb36e81afd2" integrity sha512-Qwfvh3xdqKtIznjX9lz2D458r7dJPP8l6r4GQkIdWQouZwHQK0mVT88uwiU2bdTU2OtT1uOlKpRciUWldpG0yQ== dependencies: "@octokit/request" "^6.0.0" "@octokit/types" "^9.0.0" universal-user-agent "^6.0.0" "@octokit/oauth-authorization-url@^4.3.1": version "4.3.3" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-4.3.3.tgz#6a6ef38f243086fec882b62744f39b517528dfb9" integrity sha512-lhP/t0i8EwTmayHG4dqLXgU+uPVys4WD/qUNvC+HfB1S1dyqULm5Yx9uKc1x79aP66U1Cb4OZeW8QU/RA9A4XA== "@octokit/oauth-authorization-url@^5.0.0": version "5.0.0" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz#029626ce87f3b31addb98cd0d2355c2381a1c5a1" integrity sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg== "@octokit/oauth-methods@^1.1.0": version "1.2.6" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-1.2.6.tgz#b9ac65e374b2cc55ee9dd8dcdd16558550438ea7" integrity sha512-nImHQoOtKnSNn05uk2o76om1tJWiAo4lOu2xMAHYsNr0fwopP+Dv+2MlGvaMMlFjoqVd3fF3X5ZDTKCsqgmUaQ== dependencies: "@octokit/oauth-authorization-url" "^4.3.1" "@octokit/request" "^5.4.14" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" "@octokit/oauth-methods@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-2.0.4.tgz#6abd9593ca7f91fe5068375a363bd70abd5516dc" integrity sha512-RDSa6XL+5waUVrYSmOlYROtPq0+cfwppP4VaQY/iIei3xlFb0expH6YNsxNrZktcLhJWSpm9uzeom+dQrXlS3A== dependencies: "@octokit/oauth-authorization-url" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" "@octokit/openapi-types@^12.11.0": version "12.11.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.11.0.tgz#da5638d64f2b919bca89ce6602d059f1b52d3ef0" integrity sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ== "@octokit/openapi-types@^14.0.0": version "14.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-14.0.0.tgz#949c5019028c93f189abbc2fb42f333290f7134a" integrity sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw== "@octokit/openapi-types@^16.0.0": version "16.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-16.0.0.tgz#d92838a6cd9fb4639ca875ddb3437f1045cc625e" integrity sha512-JbFWOqTJVLHZSUUoF4FzAZKYtqdxWu9Z5m2QQnOyEa04fOFljvyh7D3GYKbfuaSWisqehImiVIMG4eyJeP5VEA== "@octokit/plugin-paginate-rest@^2.16.8": version "2.21.3" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz#7f12532797775640dbb8224da577da7dc210c87e" integrity sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw== dependencies: "@octokit/types" "^6.40.0" "@octokit/plugin-paginate-rest@^6.0.0": version "6.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.0.0.tgz#f34b5a7d9416019126042cd7d7b811e006c0d561" integrity sha512-Sq5VU1PfT6/JyuXPyt04KZNVsFOSBaYOAq2QRZUwzVlI10KFvcbUo8lR258AAQL1Et60b0WuVik+zOWKLuDZxw== dependencies: "@octokit/types" "^9.0.0" "@octokit/plugin-request-log@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85" integrity sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA== "@octokit/plugin-rest-endpoint-methods@^5.12.0": version "5.16.2" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz#7ee8bf586df97dd6868cf68f641354e908c25342" integrity sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw== dependencies: "@octokit/types" "^6.39.0" deprecation "^2.3.1" "@octokit/plugin-rest-endpoint-methods@^7.0.0": version "7.0.1" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.0.1.tgz#f7ebe18144fd89460f98f35a587b056646e84502" integrity sha512-pnCaLwZBudK5xCdrR823xHGNgqOzRnJ/mpC/76YPpNP7DybdsJtP7mdOwh+wYZxK5jqeQuhu59ogMI4NRlBUvA== dependencies: "@octokit/types" "^9.0.0" deprecation "^2.3.1" "@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0": version "2.1.0" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677" integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg== dependencies: "@octokit/types" "^6.0.3" deprecation "^2.0.0" once "^1.4.0" "@octokit/request-error@^3.0.0": version "3.0.2" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-3.0.2.tgz#f74c0f163d19463b87528efe877216c41d6deb0a" integrity sha512-WMNOFYrSaX8zXWoJg9u/pKgWPo94JXilMLb2VManNOby9EZxrQaBe/QSC4a1TzpAlpxofg2X/jMnCyZgL6y7eg== dependencies: "@octokit/types" "^8.0.0" deprecation "^2.0.0" once "^1.4.0" "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3": version "5.6.3" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0" integrity sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A== dependencies: "@octokit/endpoint" "^6.0.1" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.16.1" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/request@^6.0.0": version "6.2.2" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.2.tgz#a2ba5ac22bddd5dcb3f539b618faa05115c5a255" integrity sha512-6VDqgj0HMc2FUX2awIs+sM6OwLgwHvAi4KCK3mT2H2IKRt6oH9d0fej5LluF5mck1lRR/rFWN0YIDSYXYSylbw== dependencies: "@octokit/endpoint" "^7.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/rest@^18.12.0": version "18.12.0" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881" integrity sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q== dependencies: "@octokit/core" "^3.5.1" "@octokit/plugin-paginate-rest" "^2.16.8" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^5.12.0" "@octokit/rest@^19.0.7": version "19.0.7" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.7.tgz#d2e21b4995ab96ae5bfae50b4969da7e04e0bb70" integrity sha512-HRtSfjrWmWVNp2uAkEpQnuGMJsu/+dBr47dRc5QVgsCbnIc1+GFEaoKBWkYG+zjrsHpSqcAElMio+n10c0b5JA== dependencies: "@octokit/core" "^4.1.0" "@octokit/plugin-paginate-rest" "^6.0.0" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^7.0.0" "@octokit/types@^5.0.0": version "5.2.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.2.0.tgz#d075dc23bf293f540739250b6879e2c1be2fc20c" integrity sha512-XjOk9y4m8xTLIKPe1NFxNWBdzA2/z3PFFA/bwf4EoH6oS8hM0Y46mEa4Cb+KCyj/tFDznJFahzQ0Aj3o1FYq4A== dependencies: "@types/node" ">= 8" "@octokit/types@^6.0.3", "@octokit/types@^6.10.0", "@octokit/types@^6.12.2", "@octokit/types@^6.16.1", "@octokit/types@^6.39.0", "@octokit/types@^6.40.0": version "6.41.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.41.0.tgz#e58ef78d78596d2fb7df9c6259802464b5f84a04" integrity sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg== dependencies: "@octokit/openapi-types" "^12.11.0" "@octokit/types@^8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-8.0.0.tgz#93f0b865786c4153f0f6924da067fe0bb7426a9f" integrity sha512-65/TPpOJP1i3K4lBJMnWqPUJ6zuOtzhtagDvydAWbEXpbFYA0oMKKyLb95NFZZP0lSh/4b6K+DQlzvYQJQQePg== dependencies: "@octokit/openapi-types" "^14.0.0" "@octokit/types@^9.0.0": version "9.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-9.0.0.tgz#6050db04ddf4188ec92d60e4da1a2ce0633ff635" integrity sha512-LUewfj94xCMH2rbD5YJ+6AQ4AVjFYTgpp6rboWM5T7N3IsIF65SBEOVcYMGAEzO/kKNiNaW4LoWtoThOhH06gw== dependencies: "@octokit/openapi-types" "^16.0.0" "@opentelemetry/api@^1.0.1": version "1.0.4" resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.0.4.tgz#a167e46c10d05a07ab299fc518793b0cff8f6924" integrity sha512-BuJuXRSJNQ3QoKA6GWWDyuLpOUck+9hAXNMCnrloc1aWVoy6Xq6t9PUV08aBZ4Lutqq2LEHM486bpZqoViScog== "@primer/octicons@^10.0.0": version "10.0.0" resolved "https://registry.yarnpkg.com/@primer/octicons/-/octicons-10.0.0.tgz#81e94ed32545dfd3472c8625a5b345f3ea4c153d" integrity sha512-iuQubq62zXZjPmaqrsfsCZUqIJgZhmA6W0tKzIKGRbkoLnff4TFFCL87hfIRATZ5qZPM4m8ioT8/bXI7WVa9WQ== dependencies: object-assign "^4.1.1" "@sindresorhus/is@^4.0.0": version "4.6.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" integrity sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw== "@szmarczak/http-timer@^4.0.5": version "4.0.6" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-4.0.6.tgz#b4a914bb62e7c272d4e5989fe4440f812ab1d807" integrity sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w== dependencies: defer-to-connect "^2.0.0" "@types/basic-auth@^1.1.3": version "1.1.3" resolved "https://registry.yarnpkg.com/@types/basic-auth/-/basic-auth-1.1.3.tgz#a787ede8310804174fbbf3d6c623ab1ccedb02cd" integrity sha512-W3rv6J0IGlxqgE2eQ2pTb0gBjaGtejQpJ6uaCjz3UQ65+TFTPC5/lAE+POfx1YLdjtxvejJzsIAfd3MxWiVmfg== dependencies: "@types/node" "*" "@types/body-parser@*": version "1.19.0" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.0.tgz#0685b3c47eb3006ffed117cdd55164b61f80538f" integrity sha512-W98JrE0j2K78swW4ukqMleo8R7h/pFETjM2DQ90MF6XK2i4LO4W3gQ71Lt4w3bfm2EvVSyWHplECvB5sK22yFQ== dependencies: "@types/connect" "*" "@types/node" "*" "@types/btoa-lite@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/btoa-lite/-/btoa-lite-1.0.0.tgz#e190a5a548e0b348adb0df9ac7fa5f1151c7cca4" integrity sha512-wJsiX1tosQ+J5+bY5LrSahHxr2wT+uME5UDwdN1kg4frt40euqA+wzECkmq4t5QbveHiJepfdThgQrPw6KiSlg== "@types/busboy@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@types/busboy/-/busboy-1.5.0.tgz#62681556cbbd2afc8d2efa6bafaa15602f0838b9" integrity sha512-ncOOhwmyFDW76c/Tuvv9MA9VGYUCn8blzyWmzYELcNGDb0WXWLSmFi7hJq25YdRBYJrmMBB5jZZwUjlJe9HCjQ== dependencies: "@types/node" "*" "@types/cacheable-request@^6.0.1": version "6.0.2" resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.2.tgz#c324da0197de0a98a2312156536ae262429ff6b9" integrity sha512-B3xVo+dlKM6nnKTcmm5ZtY/OL8bOAOd2Olee9M1zft65ox50OzjEHW91sDiU9j6cvW8Ejg1/Qkf4xd2kugApUA== dependencies: "@types/http-cache-semantics" "*" "@types/keyv" "*" "@types/node" "*" "@types/responselike" "*" "@types/chai-as-promised@*": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.1.tgz#004c27a4ac640e9590e25d8b0980cb0a6609bfd8" integrity sha512-dberBxQW/XWv6BMj0su1lV9/C9AUx5Hqu2pisuS6S4YK/Qt6vurcj/BmcbEsobIWWCQzhesNY8k73kIxx4X7Mg== dependencies: "@types/chai" "*" "@types/chai-as-promised@^7.1.3": version "7.1.3" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.3.tgz#779166b90fda611963a3adbfd00b339d03b747bd" integrity sha512-FQnh1ohPXJELpKhzjuDkPLR2BZCAqed+a6xV4MI/T3XzHfd2FlarfUGUdZYgqYe8oxkYn0fchHEeHfHqdZ96sg== dependencies: "@types/chai" "*" "@types/chai@*": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.1.7.tgz#1b8e33b61a8c09cbe1f85133071baa0dbf9fa71a" integrity sha512-2Y8uPt0/jwjhQ6EiluT0XCri1Dbplr0ZxfFXUz+ye13gaqE8u5gL5ppao1JrUYr9cIip5S6MvQzBS7Kke7U9VA== "@types/chai@^4.2.12": version "4.2.12" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.2.12.tgz#6160ae454cd89dae05adc3bb97997f488b608201" integrity sha512-aN5IAC8QNtSUdQzxu7lGBgYAOuU1tmRU4c9dIq5OKGf/SBVjXo+ffM2wEjudAWbgpOhy60nLoAGH1xm8fpCKFQ== "@types/color-name@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== "@types/concat-stream@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/concat-stream/-/concat-stream-1.6.1.tgz#24bcfc101ecf68e886aaedce60dfd74b632a1b74" integrity sha512-eHE4cQPoj6ngxBZMvVf6Hw7Mh4jMW4U9lpGmS5GBPB9RYxlFg+CHaVN7ErNY4W9XfLIEn20b4VDYaIrbq0q4uA== dependencies: "@types/node" "*" "@types/connect@*": version "3.4.33" resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.33.tgz#31610c901eca573b8713c3330abc6e6b9f588546" integrity sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A== dependencies: "@types/node" "*" "@types/debug@^4.0.0": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg== dependencies: "@types/ms" "*" "@types/dirty-chai@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@types/dirty-chai/-/dirty-chai-2.0.2.tgz#eeac4802329a41ed7815ac0c1a6360335bf77d0c" integrity sha512-BruwIN/UQEU0ePghxEX+OyjngpOfOUKJQh3cmfeq2h2Su/g001iljVi3+Y2y2EFp3IPgjf4sMrRU33Hxv1FUqw== dependencies: "@types/chai" "*" "@types/chai-as-promised" "*" "@types/eslint-scope@^3.7.3": version "3.7.4" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16" integrity sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA== dependencies: "@types/eslint" "*" "@types/estree" "*" "@types/eslint@*": version "8.4.5" resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.4.5.tgz#acdfb7dd36b91cc5d812d7c093811a8f3d9b31e4" integrity sha512-dhsC09y1gpJWnK+Ff4SGvCuSnk9DaU0BJZSzOwa6GVSg65XtTugLBITDAAzRU5duGBoXBHpdR/9jHGxJjNflJQ== dependencies: "@types/estree" "*" "@types/json-schema" "*" "@types/estree@*": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.0.tgz#5fb2e536c1ae9bf35366eed879e827fa59ca41c2" integrity sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ== "@types/estree@^0.0.51": version "0.0.51" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== "@types/events@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" integrity sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig== dependencies: "@types/node" "*" "@types/qs" "*" "@types/range-parser" "*" "@types/express@^4.17.13": version "4.17.13" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.13.tgz#a76e2995728999bab51a33fabce1d705a3709034" integrity sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA== dependencies: "@types/body-parser" "*" "@types/express-serve-static-core" "^4.17.18" "@types/qs" "*" "@types/serve-static" "*" "@types/fs-extra@^9.0.1": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.1.tgz#91c8fc4c51f6d5dbe44c2ca9ab09310bd00c7918" integrity sha512-B42Sxuaz09MhC3DDeW5kubRcQ5by4iuVQ0cRRWM2lggLzAa/KVom0Aft/208NgMvNQQZ86s5rVcqDdn/SH0/mg== dependencies: "@types/node" "*" "@types/glob@^7.1.1": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" integrity sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w== dependencies: "@types/events" "*" "@types/minimatch" "*" "@types/node" "*" "@types/http-cache-semantics@*": version "4.0.1" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ== "@types/is-empty@^1.0.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/is-empty/-/is-empty-1.2.0.tgz#16bc578060c9b0b6953339eea906c255a375bf86" integrity sha512-brJKf2boFhUxTDxlpI7cstwiUtA2ovm38UzFTi9aZI6//ARncaV+Q5ALjCaJqXaMtdZk/oPTJnSutugsZR6h8A== "@types/js-yaml@^4.0.0": version "4.0.2" resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-4.0.2.tgz#4117a7a378593a218e9d6f0ef44ce6d5d9edf7fa" integrity sha512-KbeHS/Y4R+k+5sWXEYzAZKuB1yQlZtEghuhRxrVRLaqhtoG5+26JwQsa4HyS3AWX8v1Uwukma5HheduUDskasA== "@types/json-buffer@~3.0.0": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/json-buffer/-/json-buffer-3.0.0.tgz#85c1ff0f0948fc159810d4b5be35bf8c20875f64" integrity sha512-3YP80IxxFJB4b5tYC2SUPwkg0XQLiu0nWvhRgEatgjf+29IcWO9X1k8xRv5DGssJ/lCrjYTjQPcobJr2yWIVuQ== "@types/json-schema@*", "@types/json-schema@^7.0.8": version "7.0.11" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== "@types/json-schema@^7.0.3": version "7.0.3" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.3.tgz#bdfd69d61e464dcc81b25159c270d75a73c1a636" integrity sha512-Il2DtDVRGDcqjDtE+rF8iqg1CArehSK84HZJCT7AMITlyXRBpuPhqGLDQMowraqqu1coEaimg4ZOqggt6L6L+A== "@types/json-schema@^7.0.4": version "7.0.4" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339" integrity sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA== "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= "@types/jsonwebtoken@^9.0.0": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz#29b1369c4774200d6d6f63135bf3d1ba3ef997a4" integrity sha512-c5ltxazpWabia/4UzhIoaDcIza4KViOQhdbjRlfcIGVnsE3c3brkz9Z+F/EeJIECOQP7W7US2hNE930cWWkPiw== dependencies: "@types/node" "*" "@types/keyv@*": version "3.1.4" resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.4.tgz#3ccdb1c6751b0c7e52300bcdacd5bcbf8faa75b6" integrity sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg== dependencies: "@types/node" "*" "@types/klaw@^3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@types/klaw/-/klaw-3.0.1.tgz#29f90021c0234976aa4eb97efced9cb6db9fa8b3" integrity sha512-acnF3n9mYOr1aFJKFyvfNX0am9EtPUsYPq22QUCGdJE+MVt6UyAN1jwo+PmOPqXD4K7ZS9MtxDEp/un0lxFccA== dependencies: "@types/node" "*" "@types/linkify-it@*": version "2.1.0" resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-2.1.0.tgz#ea3dd64c4805597311790b61e872cbd1ed2cd806" integrity sha512-Q7DYAOi9O/+cLLhdaSvKdaumWyHbm7HAk/bFwwyTuU0arR5yyCeW5GOoqt4tJTpDRxhpx9Q8kQL6vMpuw9hDSw== "@types/lru-cache@^5.1.0": version "5.1.0" resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-5.1.0.tgz#57f228f2b80c046b4a1bd5cac031f81f207f4f03" integrity sha512-RaE0B+14ToE4l6UqdarKPnXwVDuigfFv+5j9Dze/Nqr23yyuqdNvzcZi3xB+3Agvi5R4EOgAksfv3lXX4vBt9w== "@types/markdown-it@^12.0.0": version "12.2.3" resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51" integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ== dependencies: "@types/linkify-it" "*" "@types/mdurl" "*" "@types/mdast@^3.0.0": version "3.0.7" resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.7.tgz#cba63d0cc11eb1605cea5c0ad76e02684394166b" integrity sha512-YwR7OK8aPmaBvMMUi+pZXBNoW2unbVbfok4YRqGMJBe1dpDlzpRkJrYEYmvjxgs5JhuQmKfDexrN98u941Zasg== dependencies: "@types/unist" "*" "@types/mdurl@*": version "1.0.2" resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9" integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA== "@types/mime@*": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-2.0.1.tgz#dc488842312a7f075149312905b5e3c0b054c79d" integrity sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw== "@types/mime@^1": version "1.3.2" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a" integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw== "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/minimist@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= "@types/mocha@^7.0.2": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-7.0.2.tgz#b17f16cf933597e10d6d78eae3251e692ce8b0ce" integrity sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w== "@types/ms@*": version "0.7.31" resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197" integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA== "@types/node-fetch@^2.5.0": version "2.6.1" resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.1.tgz#8f127c50481db65886800ef496f20bbf15518975" integrity sha512-oMqjURCaxoSIsHSr1E47QHzbmzNR5rK8McHuNb11BOM9cHcIK3Avy0s/b2JlXHoQGTYS3NsvWzV1M0iK7l0wbA== dependencies: "@types/node" "*" form-data "^3.0.0" "@types/node@*": version "12.6.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.1.tgz#d5544f6de0aae03eefbb63d5120f6c8be0691946" integrity sha512-rp7La3m845mSESCgsJePNL/JQyhkOJA6G4vcwvVgkDAwHhGdq5GCumxmPjEk1MZf+8p5ZQAUE7tqgQRQTXN7uQ== "@types/node@>= 8": version "14.0.27" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.27.tgz#a151873af5a5e851b51b3b065c9e63390a9e0eb1" integrity sha512-kVrqXhbclHNHGu9ztnAwSncIgJv/FaxmzXJvGXNdcCpV1b8u1/Mi6z6m0vwy0LzKeXFTPLH0NzwmoJ3fNCIq0g== "@types/node@^11.13.7": version "11.13.22" resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.22.tgz#91ee88ebfa25072433497f6f3150f84fa8c3a91b" integrity sha512-rOsaPRUGTOXbRBOKToy4cgZXY4Y+QSVhxcLwdEveozbk7yuudhWMpxxcaXqYizLMP3VY7OcWCFtx9lGFh5j5kg== "@types/node@^16.0.0": version "16.4.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d" integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg== "@types/node@^18.11.18": version "18.11.18" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.18.tgz#8dfb97f0da23c2293e554c5a50d61ef134d7697f" integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA== "@types/parse-json@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== "@types/qs@*": version "6.9.3" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" integrity sha512-7s9EQWupR1fTc2pSMtXRQ9w9gLOcrJn+h7HOXw4evxyvVqMi4f+q7d2tnFe3ng3SNHjtK+0EzGMGFUQX4/AQRA== "@types/range-parser@*": version "1.2.3" resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c" integrity sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA== "@types/repeat-string@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/repeat-string/-/repeat-string-1.6.1.tgz#8bb5686e662ce1d962271b0b043623bf51404cdc" integrity sha512-vdna8kjLGljgtPnYN6MBD2UwX62QE0EFLj9QlLXvg6dEu66NksXB900BNguBCMZZY2D9SSqncUskM23vT3uvWQ== "@types/responselike@*", "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA== dependencies: "@types/node" "*" "@types/semver@^7.3.3": version "7.3.3" resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.3.tgz#3ad6ed949e7487e7bda6f886b4a2434a2c3d7b1a" integrity sha512-jQxClWFzv9IXdLdhSaTf16XI3NYe6zrEbckSpb5xhKfPbWgIyAY0AFyWWWfaiDcBuj3UHmMkCIwSRqpKMTZL2Q== "@types/send@^0.14.5": version "0.14.5" resolved "https://registry.yarnpkg.com/@types/send/-/send-0.14.5.tgz#653f7d25b93c3f7f51a8994addaf8a229de022a7" integrity sha512-0mwoiK3DXXBu0GIfo+jBv4Wo5s1AcsxdpdwNUtflKm99VEMvmBPJ+/NBNRZy2R5JEYfWL/u4nAHuTUTA3wFecQ== dependencies: "@types/mime" "*" "@types/node" "*" "@types/serve-static@*": version "1.13.10" resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.13.10.tgz#f5e0ce8797d2d7cc5ebeda48a52c96c4fa47a8d9" integrity sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ== dependencies: "@types/mime" "^1" "@types/node" "*" "@types/split@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/split/-/split-1.0.0.tgz#24f7c35707450b002f203383228f5a2bc1e6c228" integrity sha512-pm9S1mkr+av0j7D6pFyqhBxXDbnbO9gqj4nb8DtGtCewvj0XhIv089SSwXrjrIizT1UquO8/h83hCut0pa3u8A== dependencies: "@types/node" "*" "@types/through" "*" "@types/stream-chain@*": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/stream-chain/-/stream-chain-2.0.0.tgz#aed7fc21ac3686bc721aebbbd971f5a857e567e4" integrity sha512-O3IRJcZi4YddlS8jgasH87l+rdNmad9uPAMmMZCfRVhumbWMX6lkBWnIqr9kokO5sx8LHp8peQ1ELhMZHbR0Gg== dependencies: "@types/node" "*" "@types/stream-json@^1.5.1": version "1.5.1" resolved "https://registry.yarnpkg.com/@types/stream-json/-/stream-json-1.5.1.tgz#ae8d1133f9f920e18c6e94b233cb57d014a47b8d" integrity sha512-Blg6GJbKVEB1J/y/2Tv+WrYiMzPTIqyuZ+zWDJtAF8Mo8A2XQh/lkSX4EYiM+qtS+GY8ThdGi6gGA9h4sjvL+g== dependencies: "@types/node" "*" "@types/stream-chain" "*" "@types/supports-color@^8.0.0": version "8.1.1" resolved "https://registry.yarnpkg.com/@types/supports-color/-/supports-color-8.1.1.tgz#1b44b1b096479273adf7f93c75fc4ecc40a61ee4" integrity sha512-dPWnWsf+kzIG140B8z2w3fr5D03TLWbOAFQl45xUpI3vcizeXriNR5VYkWZ+WTMsUHqZ9Xlt3hrxGNANFyNQfw== "@types/temp@^0.8.34": version "0.8.34" resolved "https://registry.yarnpkg.com/@types/temp/-/temp-0.8.34.tgz#03e4b3cb67cbb48c425bbf54b12230fef85540ac" integrity sha512-oLa9c5LHXgS6UimpEVp08De7QvZ+Dfu5bMQuWyMhf92Z26Q10ubEMOWy9OEfUdzW7Y/sDWVHmUaLFtmnX/2j0w== dependencies: "@types/node" "*" "@types/text-table@^0.2.0": version "0.2.2" resolved "https://registry.yarnpkg.com/@types/text-table/-/text-table-0.2.2.tgz#774c90cfcfbc8b4b0ebb00fecbe861dc8b1e8e26" integrity sha512-dGoI5Af7To0R2XE8wJuc6vwlavWARsCh3UKJPjWs1YEqGUqfgBI/j/4GX0yf19/DsDPPf0YAXWAp8psNeIehLg== "@types/through@*": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/through/-/through-0.0.29.tgz#72943aac922e179339c651fa34a4428a4d722f93" integrity sha512-9a7C5VHh+1BKblaYiq+7Tfc+EOmjMdZaD1MYtkQjSoxgB69tBjW98ry6SKsi4zEIWztLOMRuL87A3bdT/Fc/4w== dependencies: "@types/node" "*" "@types/tunnel@^0.0.3": version "0.0.3" resolved "https://registry.yarnpkg.com/@types/tunnel/-/tunnel-0.0.3.tgz#f109e730b072b3136347561fc558c9358bb8c6e9" integrity sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA== dependencies: "@types/node" "*" "@types/unist@*", "@types/unist@^2.0.0": version "2.0.6" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== "@types/unist@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e" integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ== "@types/uuid@^3.4.6": version "3.4.6" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.6.tgz#d2c4c48eb85a757bf2927f75f939942d521e3016" integrity sha512-cCdlC/1kGEZdEglzOieLDYBxHsvEOIg7kp/2FYyVR9Pxakq+Qf/inL3RKQ+PA8gOlI/NnL+fXmQH12nwcGzsHw== dependencies: "@types/node" "*" "@types/webpack-env@^1.17.0": version "1.17.0" resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0" integrity sha512-eHSaNYEyxRA5IAG0Ym/yCyf86niZUIF/TpWKofQI/CVfh5HsMEUyfE2kwFxha4ow0s5g0LfISQxpDKjbRDrizw== "@types/webpack@^5.28.0": version "5.28.0" resolved "https://registry.yarnpkg.com/@types/webpack/-/webpack-5.28.0.tgz#78dde06212f038d77e54116cfe69e88ae9ed2c03" integrity sha512-8cP0CzcxUiFuA9xGJkfeVpqmWTk9nx6CWwamRGCj95ph1SmlRRk9KlCZ6avhCbZd4L68LvYT6l1kpdEnQXrF8w== dependencies: "@types/node" "*" tapable "^2.2.0" webpack "^5" "@types/yauzl@^2.9.1": version "2.10.0" resolved "https://registry.yarnpkg.com/@types/yauzl/-/yauzl-2.10.0.tgz#b3248295276cf8c6f153ebe6a9aba0c988cb2599" integrity sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw== dependencies: "@types/node" "*" "@typescript-eslint/eslint-plugin@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.4.1.tgz#b8acea0373bd2a388ac47df44652f00bf8b368f5" integrity sha512-O+8Utz8pb4OmcA+Nfi5THQnQpHSD2sDUNw9AxNHpuYOo326HZTtG8gsfT+EAYuVrFNaLyNb2QnUNkmTRDskuRA== dependencies: "@typescript-eslint/experimental-utils" "4.4.1" "@typescript-eslint/scope-manager" "4.4.1" debug "^4.1.1" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.4.1.tgz#40613b9757fa0170de3e0043254dbb077cafac0c" integrity sha512-Nt4EVlb1mqExW9cWhpV6pd1a3DkUbX9DeyYsdoeziKOpIJ04S2KMVDO+SEidsXRH/XHDpbzXykKcMTLdTXH6cQ== dependencies: "@types/json-schema" "^7.0.3" "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" eslint-scope "^5.0.0" eslint-utils "^2.0.0" "@typescript-eslint/parser@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.4.1.tgz#25fde9c080611f303f2f33cedb145d2c59915b80" integrity sha512-S0fuX5lDku28Au9REYUsV+hdJpW/rNW0gWlc4SXzF/kdrRaAVX9YCxKpziH7djeWT/HFAjLZcnY7NJD8xTeUEg== dependencies: "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" debug "^4.1.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.4.1.tgz#d19447e60db2ce9c425898d62fa03b2cce8ea3f9" integrity sha512-2oD/ZqD4Gj41UdFeWZxegH3cVEEH/Z6Bhr/XvwTtGv66737XkR4C9IqEkebCuqArqBJQSj4AgNHHiN1okzD/wQ== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.4.1.tgz#c507b35cf523bc7ba00aae5f75ee9b810cdabbc1" integrity sha512-KNDfH2bCyax5db+KKIZT4rfA8rEk5N0EJ8P0T5AJjo5xrV26UAzaiqoJCxeaibqc0c/IvZxp7v2g3difn2Pn3w== "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.4.1.tgz#598f6de488106c2587d47ca2462c60f6e2797cb8" integrity sha512-wP/V7ScKzgSdtcY1a0pZYBoCxrCstLrgRQ2O9MmCUZDtmgxCO/TCqOTGRVwpP4/2hVfqMz/Vw1ZYrG8cVxvN3g== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" debug "^4.1.1" globby "^11.0.1" is-glob "^4.0.1" lodash "^4.17.15" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.4.1.tgz#1769dc7a9e2d7d2cfd3318b77ed8249187aed5c3" integrity sha512-H2JMWhLaJNeaylSnMSQFEhT/S/FsJbebQALmoJxMPMxLtlVAMy2uJP/Z543n9IizhjRayLSqoInehCeNW9rWcw== dependencies: "@typescript-eslint/types" "4.4.1" eslint-visitor-keys "^2.0.0" "@vscode/l10n@^0.0.10": version "0.0.10" resolved "https://registry.yarnpkg.com/@vscode/l10n/-/l10n-0.0.10.tgz#9c513107c690c0dd16e3ec61e453743de15ebdb0" integrity sha512-E1OCmDcDWa0Ya7vtSjp/XfHFGqYJfh+YPC1RkATU71fTac+j1JjCcB3qwSzmlKAighx2WxhLlfhS0RwAN++PFQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" integrity sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw== dependencies: "@webassemblyjs/helper-numbers" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz#f6c61a705f0fd7a6aecaa4e8198f23d9dc179e4f" integrity sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz#1a63192d8788e5c012800ba6a7a46c705288fd16" integrity sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz#832a900eb444884cde9a7cad467f81500f5e5ab5" integrity sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz#64d81da219fbbba1e3bd1bfc74f6e8c4e10a62ae" integrity sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ== dependencies: "@webassemblyjs/floating-point-hex-parser" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz#f328241e41e7b199d0b20c18e88429c4433295e1" integrity sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz#21ee065a7b635f319e738f0dd73bfbda281c097a" integrity sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz#963929e9bbd05709e7e12243a099180812992614" integrity sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ== dependencies: "@xtuc/ieee754" "^1.2.0" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.11.1.tgz#ce814b45574e93d76bae1fb2644ab9cdd9527aa5" integrity sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw== dependencies: "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.11.1.tgz#d1f8b764369e7c6e6bae350e854dec9a59f0a3ff" integrity sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz#ad206ebf4bf95a058ce9880a8c092c5dec8193d6" integrity sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/helper-wasm-section" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-opt" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/wast-printer" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz#86c5ea304849759b7d88c47a32f4f039ae3c8f76" integrity sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz#657b4c2202f4cf3b345f8a4c6461c8c2418985f2" integrity sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz#86ca734534f417e9bd3c67c7a1c75d8be41fb199" integrity sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz#d0c73beda8eec5426f10ae8ef55cee5e7084c2f0" integrity sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg== dependencies: "@webassemblyjs/ast" "1.11.1" "@xtuc/long" "4.2.2" "@webpack-cli/configtest@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== "@webpack-cli/info@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== dependencies: envinfo "^7.7.3" "@webpack-cli/serve@^1.7.0": version "1.7.0" resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== "@xtuc/ieee754@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== "@xtuc/[email protected]": version "4.2.2" resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw== dependencies: mime-types "~2.1.34" negotiator "0.6.3" acorn-import-assertions@^1.7.6: version "1.8.0" resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz#ba2b5939ce62c238db6d93d81c9b111b29b855e9" integrity sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw== acorn-jsx@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.2.0.tgz#4c66069173d6fdd68ed85239fc256226182b2ebe" integrity sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ== acorn@^7.1.1, acorn@^7.2.0: version "7.3.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.3.1.tgz#85010754db53c3fbaf3b9ea3e083aa5c5d147ffd" integrity sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA== acorn@^8.5.0, acorn@^8.7.1: version "8.8.2" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.2.tgz#1b2f25db02af965399b9776b0c2c391276d37c4a" integrity sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw== aggregate-error@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.0.1.tgz#db2fe7246e536f40d9b5442a39e117d7dd6a24e0" integrity sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA== dependencies: clean-stack "^2.0.0" indent-string "^4.0.0" ajv-keywords@^3.4.1: version "3.4.1" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== ajv-keywords@^3.5.2: version "3.5.2" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d" integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.2, ajv@^6.12.5: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== dependencies: fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" json-schema-traverse "^0.4.1" uri-js "^4.2.2" ansi-colors@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: version "4.3.1" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.1.tgz#a5c47cc43181f1f38ffd7076837700d395522a61" integrity sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA== dependencies: type-fest "^0.11.0" ansi-regex@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.1.tgz#164daac87ab2d6f6db3a29875e2d1766582dabed" integrity sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g== ansi-regex@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== ansi-regex@^6.0.0: version "6.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359" integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA== dependencies: "@types/color-name" "^1.1.1" color-convert "^2.0.1" anymatch@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.0.3.tgz#2fb624fe0e84bccab00afee3d0006ed310f22f09" integrity sha512-c6IvoeBECQlMVuYUjSwimnhmztImpErfxJzWZhIQinIvQWoGOnB0dLIgifbPHQt5heS6mNlaZG16f06H3C8t1g== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" integrity sha1-ml9pkFGx5wczKPKgCJaLZOopVdI= array-includes@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.0.3.tgz#184b48f62d92d7452bb31b323165c7f8bd02266d" integrity sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0= dependencies: define-properties "^1.1.2" es-abstract "^1.7.0" array-includes@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.1.tgz#cdd67e6852bdf9c1215460786732255ed2459348" integrity sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0" is-string "^1.0.5" array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= array.prototype.flat@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz#0de82b426b0318dbfdb940089e38b043d37f6c7b" integrity sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" arrify@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= assertion-error@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b" integrity sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw== astral-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg== astral-regex@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== async@^3.2.0: version "3.2.4" resolved "https://registry.yarnpkg.com/async/-/async-3.2.4.tgz#2d22e00f8cddeb5fde5dd33522b56d1cf569a81c" integrity sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ== asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= at-least-node@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== bail@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/bail/-/bail-2.0.1.tgz#d676736373a374058a935aec81b94c12ba815771" integrity sha512-d5FoTAr2S5DSUPKl85WNm2yUwsINN8eidIdIwsOge2t33DaOfOdSmmsI11jMN3GmALCXaw+Y6HMVHDzePshFAA== balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== before-after-hook@^2.2.0: version "2.2.3" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.3.tgz#c51e809c81a4e354084422b9b26bad88249c517c" integrity sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ== big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== binary-extensions@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== [email protected]: version "1.20.1" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.1.tgz#b1812a8912c195cd371a3ee5e66faa2338a5c668" integrity sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw== dependencies: bytes "3.1.2" content-type "~1.0.4" debug "2.6.9" depd "2.0.0" destroy "1.2.0" http-errors "2.0.0" iconv-lite "0.4.24" on-finished "2.4.1" qs "6.11.0" raw-body "2.5.1" type-is "~1.6.18" unpipe "1.0.0" boolean@^3.0.1: version "3.2.0" resolved "https://registry.yarnpkg.com/boolean/-/boolean-3.2.0.tgz#9e5294af4e98314494cbb17979fa54ca159f116b" integrity sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" brace-expansion@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" braces@^3.0.1, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: fill-range "^7.0.1" browserslist@^4.14.5: version "4.21.2" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.2.tgz#59a400757465535954946a400b841ed37e2b4ecf" integrity sha512-MonuOgAtUB46uP5CezYbRaYKBNt2LxP0yX+Pmj4LkcDFGkn9Cbpi83d9sCjwQDErXsIJSzY5oKGDbgOlF/LPAA== dependencies: caniuse-lite "^1.0.30001366" electron-to-chromium "^1.4.188" node-releases "^2.0.6" update-browserslist-db "^1.0.4" btoa-lite@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/btoa-lite/-/btoa-lite-1.0.0.tgz#337766da15801210fdd956c22e9c6891ab9d0337" integrity sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA== buffer-crc32@~0.2.3: version "0.2.13" resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" integrity sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ== [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk= buffer-from@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== buffer-from@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== buffer@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== dependencies: base64-js "^1.3.1" ieee754 "^1.2.1" builtins@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/builtins/-/builtins-4.0.0.tgz#a8345420de82068fdc4d6559d0456403a8fb1905" integrity sha512-qC0E2Dxgou1IHhvJSLwGDSTvokbRovU5zZFuDY6oY8Y2lF3nGt5Ad8YZK7GMtqzY84Wu7pXTPeHQeHcXSXsRhw== dependencies: semver "^7.0.0" [email protected]: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== cacheable-lookup@^5.0.3: version "5.0.4" resolved "https://registry.yarnpkg.com/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz#5a6b865b2c44357be3d5ebc2a467b032719a7005" integrity sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA== cacheable-request@^7.0.2: version "7.0.2" resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-7.0.2.tgz#ea0d0b889364a25854757301ca12b2da77f91d27" integrity sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew== dependencies: clone-response "^1.0.2" get-stream "^5.1.0" http-cache-semantics "^4.0.0" keyv "^4.0.0" lowercase-keys "^2.0.0" normalize-url "^6.0.1" responselike "^2.0.0" call-bind@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== dependencies: function-bind "^1.1.1" get-intrinsic "^1.0.2" callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== camelcase@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== caniuse-lite@^1.0.30001366: version "1.0.30001367" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001367.tgz#2b97fe472e8fa29c78c5970615d7cd2ee414108a" integrity sha512-XDgbeOHfifWV3GEES2B8rtsrADx4Jf+juKX2SICJcaUhjYBO3bR96kvEIHa15VU6ohtOhBZuPGGYGbXMRn0NCw== chai@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/chai/-/chai-4.2.0.tgz#760aa72cf20e3795e84b12877ce0e83737aa29e5" integrity sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw== dependencies: assertion-error "^1.1.0" check-error "^1.0.2" deep-eql "^3.0.1" get-func-name "^2.0.0" pathval "^1.1.0" type-detect "^4.0.5" chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" chalk@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" chalk@^4.0.0, chalk@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" character-entities-legacy@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz#57f4d00974c696e8f74e9f493e7fcb75b44d7ee7" integrity sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA== character-entities@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-2.0.0.tgz#508355fcc8c73893e0909efc1a44d28da2b6fdf3" integrity sha512-oHqMj3eAuJ77/P5PaIRcqk+C3hdfNwyCD2DAUcD5gyXkegAuF2USC40CEqPscDk4I8FRGMTojGJQkXDsN5QlJA== character-reference-invalid@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-2.0.0.tgz#a0bdeb89c051fe7ed5d3158b2f06af06984f2813" integrity sha512-pE3Z15lLRxDzWJy7bBHBopRwfI20sbrMVLQTC7xsPglCHf4Wv1e167OgYAFP78co2XlhojDyAqA+IAJse27//g== chardet@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== check-error@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= check-for-leaks@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/check-for-leaks/-/check-for-leaks-1.2.1.tgz#4ac108ee3f8e6b99f5ad36f6b98cba1d7f4816d0" integrity sha512-9OdOSRZY6N0w5JCdJpqsC5MkD6EPGYpHmhtf4l5nl3DRETDZshP6C1EGN/vVhHDTY6AsOK3NhdFfrMe3NWZl7g== dependencies: anymatch "^3.0.2" minimist "^1.2.0" parse-gitignore "^0.4.0" walk-sync "^0.3.2" chokidar@^3.0.0: version "3.5.2" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== dependencies: anymatch "~3.1.2" braces "~3.0.2" glob-parent "~5.1.2" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" readdirp "~3.6.0" optionalDependencies: fsevents "~2.3.2" chownr@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== chrome-trace-event@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" integrity sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ== dependencies: tslib "^1.9.0" chromium-pickle-js@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz#04a106672c18b085ab774d983dfa3ea138f22205" integrity sha1-BKEGZywYsIWrd02YPfo+oTjyIgU= clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== cli-cursor@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" integrity sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU= dependencies: restore-cursor "^2.0.0" cli-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== dependencies: restore-cursor "^3.1.0" cli-spinners@^2.0.0, cli-spinners@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== [email protected], cli-truncate@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== dependencies: slice-ansi "^3.0.0" string-width "^4.2.0" cli-width@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" integrity sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw== clone-deep@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== dependencies: is-plain-object "^2.0.4" kind-of "^6.0.2" shallow-clone "^3.0.0" clone-response@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.2.tgz#d1dc973920314df67fbeb94223b4ee350239e96b" integrity sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws= dependencies: mimic-response "^1.0.0" clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4= [email protected]: version "3.1.0" resolved "https://registry.yarnpkg.com/co/-/co-3.1.0.tgz#4ea54ea5a08938153185e15210c68d9092bc1b78" integrity sha1-TqVOpaCJOBUxheFSEMaNkJK8G3g= color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-convert@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== dependencies: color-name "~1.1.4" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= color-name@~1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== colorette@^2.0.14: version "2.0.19" resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== [email protected]: version "1.4.0" resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== colors@^1.1.2: version "1.3.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.3.tgz#39e005d546afe01e01f9c4ca8fa50f686a01205d" integrity sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg== combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== dependencies: delayed-stream "~1.0.0" commander@^2.20.0, commander@^2.9.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== commander@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== commander@^5.0.0, commander@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== commander@^7.0.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== commander@~9.4.1: version "9.4.1" resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.1.tgz#d1dd8f2ce6faf93147295c0df13c7c21141cfbdd" integrity sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw== compress-brotli@^1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/compress-brotli/-/compress-brotli-1.3.8.tgz#0c0a60c97a989145314ec381e84e26682e7b38db" integrity sha512-lVcQsjhxhIXsuupfy9fmZUFtAIdBmXA7EGY6GBdgZ++qkM9zG4YFT8iU7FoBxzryNDMOpD1HIFHUSX4D87oqhQ== dependencies: "@types/json-buffer" "~3.0.0" json-buffer "~3.0.1" [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== concat-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-2.0.0.tgz#414cf5af790a48c60ab9be4527d56d5e41133cb1" integrity sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A== dependencies: buffer-from "^1.0.0" inherits "^2.0.3" readable-stream "^3.0.2" typedarray "^0.0.6" contains-path@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo= [email protected]: version "0.5.4" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== dependencies: safe-buffer "5.2.1" content-type@~1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA== [email protected]: version "1.0.6" resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw= [email protected]: version "0.5.0" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b" integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw== core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= cosmiconfig@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982" integrity sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg== dependencies: "@types/parse-json" "^4.0.0" import-fresh "^3.1.0" parse-json "^5.0.0" path-type "^4.0.0" yaml "^1.7.2" cross-spawn@^6.0.5: version "6.0.5" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== dependencies: nice-try "^1.0.4" path-key "^2.0.1" semver "^5.5.0" shebang-command "^1.2.0" which "^1.2.9" cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== dependencies: path-key "^3.1.0" shebang-command "^2.0.0" which "^2.0.1" debug-log@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f" integrity sha1-IwdjLUwEOCuN+KMvcLiVBG1SdF8= [email protected], debug@^2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" debug@^3.1.0: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" debug@^4.0.0: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== dependencies: ms "2.1.2" debug@^4.0.1, debug@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== dependencies: ms "^2.1.1" debug@^4.1.0, debug@^4.3.3, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" decode-named-character-reference@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz#daabac9690874c394c81e4162a0304b35d824f0e" integrity sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg== dependencies: character-entities "^2.0.0" decompress-response@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== dependencies: mimic-response "^3.1.0" dedent@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw= deep-eql@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df" integrity sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw== dependencies: type-detect "^4.0.0" deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== deep-is@^0.1.3, deep-is@~0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= defaults@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.3.tgz#c656051e9817d9ff08ed881477f3fe4019f3ef7d" integrity sha1-xlYFHpgX2f8I7YgUd/P+QBnz730= dependencies: clone "^1.0.2" defer-to-connect@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587" integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg== define-properties@^1.1.2, define-properties@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" deglob@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/deglob/-/deglob-4.0.1.tgz#0685c6383992fd6009be10653a2b1116696fad55" integrity sha512-/g+RDZ7yf2HvoW+E5Cy+K94YhgcFgr6C8LuHZD1O5HoNPkf3KY6RfXJ0DBGlB/NkLi5gml+G9zqRzk9S0mHZCg== dependencies: find-root "^1.0.0" glob "^7.0.5" ignore "^5.0.0" pkg-config "^1.1.0" run-parallel "^1.1.2" uniq "^1.0.1" delayed-stream@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== dequal@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== detect-node@^2.0.4: version "2.1.0" resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== diff@^3.1.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== diff@^5.0.0: version "5.1.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.1.0.tgz#bc52d298c5ea8df9194800224445ed43ffc87e40" integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== dependencies: path-type "^4.0.0" [email protected]: version "1.5.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" integrity sha1-N53Ocw9hZvds76TmcHoVmwLFpvo= dependencies: esutils "^2.0.2" isarray "^1.0.0" doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" integrity sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw== dependencies: esutils "^2.0.2" doctrine@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== dependencies: esutils "^2.0.2" dotenv-safe@^4.0.4: version "4.0.4" resolved "https://registry.yarnpkg.com/dotenv-safe/-/dotenv-safe-4.0.4.tgz#8b0e7ced8e70b1d3c5d874ef9420e406f39425b3" integrity sha1-iw587Y5wsdPF2HTvlCDkBvOUJbM= dependencies: dotenv "^4.0.0" dotenv@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-4.0.0.tgz#864ef1379aced55ce6f95debecdce179f7a0cd1d" integrity sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0= dugite@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/dugite/-/dugite-2.3.0.tgz#ff6fdb4c899f84ed6695c9e01eaf4364a6211f13" integrity sha512-78zuD3p5lx2IS8DilVvHbXQXRo+hGIb3EAshTEC3ZyBLyArKegA8R/6c4Ne1aUlx6JRf3wmKNgYkdJOYMyj9aA== dependencies: progress "^2.0.3" tar "^6.1.11" duplexer@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= [email protected]: version "1.0.11" resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf" integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ== dependencies: safe-buffer "^5.0.1" [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.188: version "1.4.195" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.195.tgz#139b2d95a42a3f17df217589723a1deac71d1473" integrity sha512-vefjEh0sk871xNmR5whJf9TEngX+KTKS3hOHpjoMpauKkwlGwtMz1H8IaIjAT/GNnX0TbGwAdmVoXCAzXf+PPg== emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== emoji-regex@^9.2.2: version "9.2.2" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" integrity sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q== encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= end-of-stream@^1.1.0: version "1.4.4" resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" enhanced-resolve@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" integrity sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng== dependencies: graceful-fs "^4.1.2" memory-fs "^0.4.0" tapable "^1.0.0" enhanced-resolve@^5.10.0: version "5.12.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz#300e1c90228f5b570c4d35babf263f6da7155634" integrity sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ== dependencies: graceful-fs "^4.2.4" tapable "^2.2.0" enquirer@^2.3.5: version "2.3.6" resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== dependencies: ansi-colors "^4.1.1" ensure-posix-path@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/ensure-posix-path/-/ensure-posix-path-1.1.1.tgz#3c62bdb19fa4681544289edb2b382adc029179ce" integrity sha512-VWU0/zXzVbeJNXvME/5EmLuEj2TauvoaTz6aFYK1Z92JCBlDlZ3Gu0tuGR42kpW1754ywTs+QB0g5TP0oj9Zaw== entities@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== entities@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== env-paths@^2.2.0, env-paths@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== envinfo@^7.7.3: version "7.8.1" resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== errno@^0.1.3: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== dependencies: prr "~1.0.1" error-ex@^1.2.0, error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" es-abstract@^1.17.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.5: version "1.17.6" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" is-callable "^1.2.0" is-regex "^1.1.0" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" string.prototype.trimend "^1.0.1" string.prototype.trimstart "^1.0.1" es-abstract@^1.7.0: version "1.13.0" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9" integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg== dependencies: es-to-primitive "^1.2.0" function-bind "^1.1.1" has "^1.0.3" is-callable "^1.1.4" is-regex "^1.0.4" object-keys "^1.0.12" es-module-lexer@^0.9.0: version "0.9.3" resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== es-to-primitive@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es-to-primitive@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es6-error@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/es6-error/-/es6-error-4.1.1.tgz#9e3af407459deed47e9a91f9b885a84eb05c561d" integrity sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg== es6-object-assign@^1.0.3: version "1.1.0" resolved "https://registry.yarnpkg.com/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= escape-string-regexp@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== [email protected]: version "8.1.0" resolved "https://registry.yarnpkg.com/eslint-config-standard-jsx/-/eslint-config-standard-jsx-8.1.0.tgz#314c62a0e6f51f75547f89aade059bec140edfc7" integrity sha512-ULVC8qH8qCqbU792ZOO6DaiaZyHNS/5CZt3hKqHkEhVlhPEPN3nfBqqxJCyp59XrjIBZPu1chMYe9T2DXZ7TMw== [email protected], eslint-config-standard@^14.1.1: version "14.1.1" resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-14.1.1.tgz#830a8e44e7aef7de67464979ad06b406026c56ea" integrity sha512-Z9B+VR+JIXRxz21udPTL9HpFMyoMUEeX1G251EQ6e05WD9aPVtVBn09XUmZ259wCMlCDmYDSZG62Hhm+ZTJcUg== eslint-import-resolver-node@^0.3.2, eslint-import-resolver-node@^0.3.3: version "0.3.4" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz#85ffa81942c25012d8231096ddf679c03042c717" integrity sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA== dependencies: debug "^2.6.9" resolve "^1.13.1" eslint-module-utils@^2.4.0, eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" integrity sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA== dependencies: debug "^2.6.9" pkg-dir "^2.0.0" eslint-plugin-es@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-2.0.0.tgz#0f5f5da5f18aa21989feebe8a73eadefb3432976" integrity sha512-f6fceVtg27BR02EYnBhgWLFQfK6bN4Ll0nQFrBHOlCsAyxeZkn0NHns5O0YZOPrV1B3ramd6cgFwaoFLcSkwEQ== dependencies: eslint-utils "^1.4.2" regexpp "^3.0.0" eslint-plugin-es@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz#75a7cdfdccddc0589934aeeb384175f221c57893" integrity sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ== dependencies: eslint-utils "^2.0.0" regexpp "^3.0.0" eslint-plugin-import@^2.22.0: version "2.22.0" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz#92f7736fe1fde3e2de77623c838dd992ff5ffb7e" integrity sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg== dependencies: array-includes "^3.1.1" array.prototype.flat "^1.2.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.3" eslint-module-utils "^2.6.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.1" read-pkg-up "^2.0.0" resolve "^1.17.0" tsconfig-paths "^3.9.0" eslint-plugin-import@~2.18.0: version "2.18.2" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.18.2.tgz#02f1180b90b077b33d447a17a2326ceb400aceb6" integrity sha512-5ohpsHAiUBRNaBWAF08izwUGlbrJoJJ+W9/TBwsGoR1MnlgfwMIKrFeSjWbt6moabiXW9xNvtFz+97KHRfI4HQ== dependencies: array-includes "^3.0.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.2" eslint-module-utils "^2.4.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.0" read-pkg-up "^2.0.0" resolve "^1.11.0" eslint-plugin-mocha@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-mocha/-/eslint-plugin-mocha-7.0.1.tgz#b2e9e8ebef7836f999a83f8bab25d0e0c05f0d28" integrity sha512-zkQRW9UigRaayGm/pK9TD5RjccKXSgQksNtpsXbG9b6L5I+jNx7m98VUbZ4w1H1ArlNA+K7IOH+z8TscN6sOYg== dependencies: eslint-utils "^2.0.0" ramda "^0.27.0" eslint-plugin-node@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" integrity sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g== dependencies: eslint-plugin-es "^3.0.0" eslint-utils "^2.0.0" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-node@~10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-10.0.0.tgz#fd1adbc7a300cf7eb6ac55cf4b0b6fc6e577f5a6" integrity sha512-1CSyM/QCjs6PXaT18+zuAXsjXGIGo5Rw630rSKwokSs2jrYURQc4R5JZpoanNCqwNmepg+0eZ9L7YiRUJb8jiQ== dependencies: eslint-plugin-es "^2.0.0" eslint-utils "^1.4.2" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-promise@~4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz#845fd8b2260ad8f82564c1222fce44ad71d9418a" integrity sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw== eslint-plugin-react@~7.14.2: version "7.14.3" resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz#911030dd7e98ba49e1b2208599571846a66bdf13" integrity sha512-EzdyyBWC4Uz2hPYBiEJrKCUi2Fn+BJ9B/pJQcjw5X+x/H2Nm59S4MJIvL4O5NEE0+WbnQwEBxWY03oUk+Bc3FA== dependencies: array-includes "^3.0.3" doctrine "^2.1.0" has "^1.0.3" jsx-ast-utils "^2.1.0" object.entries "^1.1.0" object.fromentries "^2.0.0" object.values "^1.1.0" prop-types "^15.7.2" resolve "^1.10.1" eslint-plugin-standard@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.1.tgz#ff0519f7ffaff114f76d1bd7c3996eef0f6e20b4" integrity sha512-v/KBnfyaOMPmZc/dmc6ozOdWqekGp7bBGq4jLAecEfPGmfKiWS4sA8sC0LqiV9w5qmXAtXVn4M3p1jSyhY85SQ== eslint-plugin-standard@~4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.0.tgz#f845b45109c99cd90e77796940a344546c8f6b5c" integrity sha512-OwxJkR6TQiYMmt1EsNRMe5qG3GsbjlcOhbGUBY4LtavF9DsLaTcoR+j2Tdjqi23oUwKNUqX7qcn5fPStafMdlA== eslint-plugin-typescript@^0.14.0: version "0.14.0" resolved "https://registry.yarnpkg.com/eslint-plugin-typescript/-/eslint-plugin-typescript-0.14.0.tgz#068549c3f4c7f3f85d88d398c29fa96bf500884c" integrity sha512-2u1WnnDF2mkWWgU1lFQ2RjypUlmRoBEvQN02y9u+IL12mjWlkKFGEBnVsjs9Y8190bfPQCvWly1c2rYYUSOxWw== dependencies: requireindex "~1.1.0" [email protected], eslint-scope@^5.0.0, eslint-scope@^5.1.0: version "5.1.1" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== dependencies: esrecurse "^4.3.0" estraverse "^4.1.1" eslint-utils@^1.4.2, eslint-utils@^1.4.3: version "1.4.3" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f" integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q== dependencies: eslint-visitor-keys "^1.1.0" eslint-utils@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" eslint-visitor-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2" integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A== eslint-visitor-keys@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== eslint-visitor-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8" integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== eslint@^7.4.0: version "7.4.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.4.0.tgz#4e35a2697e6c1972f9d6ef2b690ad319f80f206f" integrity sha512-gU+lxhlPHu45H3JkEGgYhWhkR9wLHHEXC9FbWFnTlEkbKyZKWgWRLgf61E8zWmBuI6g5xKBph9ltg3NtZMVF8g== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^4.0.0" cross-spawn "^7.0.2" debug "^4.0.1" doctrine "^3.0.0" enquirer "^2.3.5" eslint-scope "^5.1.0" eslint-utils "^2.0.0" eslint-visitor-keys "^1.2.0" espree "^7.1.0" esquery "^1.2.0" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash "^4.17.14" minimatch "^3.0.4" natural-compare "^1.4.0" optionator "^0.9.1" progress "^2.0.0" regexpp "^3.1.0" semver "^7.2.1" strip-ansi "^6.0.0" strip-json-comments "^3.1.0" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" eslint@~6.8.0: version "6.8.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-6.8.0.tgz#62262d6729739f9275723824302fb227c8c93ffb" integrity sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^2.1.0" cross-spawn "^6.0.5" debug "^4.0.1" doctrine "^3.0.0" eslint-scope "^5.0.0" eslint-utils "^1.4.3" eslint-visitor-keys "^1.1.0" espree "^6.1.2" esquery "^1.0.1" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" inquirer "^7.0.0" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.3.0" lodash "^4.17.14" minimatch "^3.0.4" mkdirp "^0.5.1" natural-compare "^1.4.0" optionator "^0.8.3" progress "^2.0.0" regexpp "^2.0.1" semver "^6.1.2" strip-ansi "^5.2.0" strip-json-comments "^3.0.1" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" espree@^6.1.2: version "6.2.1" resolved "https://registry.yarnpkg.com/espree/-/espree-6.2.1.tgz#77fc72e1fd744a2052c20f38a5b575832e82734a" integrity sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw== dependencies: acorn "^7.1.1" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.1.0" espree@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/espree/-/espree-7.1.0.tgz#a9c7f18a752056735bf1ba14cb1b70adc3a5ce1c" integrity sha512-dcorZSyfmm4WTuTnE5Y7MEN1DyoPYy1ZR783QW1FJoenn7RailyWFsq/UL6ZAAA7uXurN9FIpYyUs3OfiIW+Qw== dependencies: acorn "^7.2.0" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.2.0" esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== esquery@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" integrity sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA== dependencies: estraverse "^4.0.0" esquery@^1.2.0: version "1.3.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.3.1.tgz#b78b5828aa8e214e29fb74c4d5b752e1c033da57" integrity sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ== dependencies: estraverse "^5.1.0" esrecurse@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== dependencies: estraverse "^5.2.0" estraverse@^4.0.0, estraverse@^4.1.1: version "4.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== estraverse@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.1.0.tgz#374309d39fd935ae500e7b92e8a6b4c720e59642" integrity sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw== estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== esutils@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== etag@~1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc= events-to-array@^1.0.1: version "1.1.2" resolved "https://registry.yarnpkg.com/events-to-array/-/events-to-array-1.1.2.tgz#2d41f563e1fe400ed4962fe1a4d5c6a7539df7f6" integrity sha1-LUH1Y+H+QA7Uli/hpNXGp1Od9/Y= events@^3.0.0, events@^3.2.0: version "3.3.0" resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== execa@^4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2" integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A== dependencies: cross-spawn "^7.0.0" get-stream "^5.0.0" human-signals "^1.1.1" is-stream "^2.0.0" merge-stream "^2.0.0" npm-run-path "^4.0.0" onetime "^5.1.0" signal-exit "^3.0.2" strip-final-newline "^2.0.0" express@^4.16.4: version "4.18.2" resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59" integrity sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ== dependencies: accepts "~1.3.8" array-flatten "1.1.1" body-parser "1.20.1" content-disposition "0.5.4" content-type "~1.0.4" cookie "0.5.0" cookie-signature "1.0.6" debug "2.6.9" depd "2.0.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" finalhandler "1.2.0" fresh "0.5.2" http-errors "2.0.0" merge-descriptors "1.0.1" methods "~1.1.2" on-finished "2.4.1" parseurl "~1.3.3" path-to-regexp "0.1.7" proxy-addr "~2.0.7" qs "6.11.0" range-parser "~1.2.1" safe-buffer "5.2.1" send "0.18.0" serve-static "1.15.0" setprototypeof "1.2.0" statuses "2.0.1" type-is "~1.6.18" utils-merge "1.0.1" vary "~1.1.2" extend@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== external-editor@^3.0.3: version "3.1.0" resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== dependencies: chardet "^0.7.0" iconv-lite "^0.4.24" tmp "^0.0.33" extract-zip@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-2.0.1.tgz#663dca56fe46df890d5f131ef4a06d22bb8ba13a" integrity sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg== dependencies: debug "^4.1.1" get-stream "^5.1.0" yauzl "^2.10.0" optionalDependencies: "@types/yauzl" "^2.9.1" fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-glob@^3.1.1: version "3.2.4" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3" integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ== dependencies: "@nodelib/fs.stat" "^2.0.2" "@nodelib/fs.walk" "^1.2.3" glob-parent "^5.1.0" merge2 "^1.3.0" micromatch "^4.0.2" picomatch "^2.2.1" fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= fastest-levenshtein@^1.0.12: version "1.0.14" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.14.tgz#9054384e4b7a78c88d01a4432dc18871af0ac859" integrity sha512-tFfWHjnuUfKE186Tfgr+jtaFc0mZTApEgKDOeyN+FwOqRkO/zK/3h1AiRd8u8CY53owL3CUmGr/oI9p/RdyLTA== fastq@^1.6.0: version "1.8.0" resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481" integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q== dependencies: reusify "^1.0.4" fault@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fault/-/fault-2.0.0.tgz#ad2198a6e28e344dcda76a7b32406b1039f0b707" integrity sha512-JsDj9LFcoC+4ChII1QpXPA7YIaY8zmqPYw7h9j5n7St7a0BBKfNnwEBAUQRBx70o2q4rs+BeSNHk8Exm6xE7fQ== dependencies: format "^0.2.0" fd-slicer@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" integrity sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g== dependencies: pend "~1.2.0" figgy-pudding@^3.5.1: version "3.5.2" resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e" integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw== figures@^3.0.0, figures@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/figures/-/figures-3.2.0.tgz#625c18bd293c604dc4a8ddb2febf0c88341746af" integrity sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg== dependencies: escape-string-regexp "^1.0.5" file-entry-cache@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-5.0.1.tgz#ca0f6efa6dd3d561333fb14515065c2fafdf439c" integrity sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g== dependencies: flat-cache "^2.0.1" fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== dependencies: to-regex-range "^5.0.1" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32" integrity sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg== dependencies: debug "2.6.9" encodeurl "~1.0.2" escape-html "~1.0.3" on-finished "2.4.1" parseurl "~1.3.3" statuses "2.0.1" unpipe "~1.0.0" find-root@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng== find-up@^2.0.0, find-up@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= dependencies: locate-path "^2.0.0" find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" find-up@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== dependencies: locate-path "^5.0.0" path-exists "^4.0.0" flat-cache@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0" integrity sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA== dependencies: flatted "^2.0.0" rimraf "2.6.3" write "1.0.3" flatted@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== folder-hash@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/folder-hash/-/folder-hash-2.1.2.tgz#7109f9cd0cbca271936d1b5544b156d6571e6cfd" integrity sha512-PmMwEZyNN96EMshf7sek4OIB7ADNsHOJ7VIw7pO0PBI0BNfEsi7U8U56TBjjqqwQ0WuBv8se0HEfmbw5b/Rk+w== dependencies: debug "^3.1.0" graceful-fs "~4.1.11" minimatch "~3.0.4" form-data@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" form-data@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" format@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" integrity sha1-1hcBB+nv3E7TDJ3DkBbflCtctYs= [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow== [email protected]: version "0.5.2" resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac= fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" integrity sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ== dependencies: graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^2.0.0" fs-extra@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9" integrity sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw== dependencies: graceful-fs "^4.1.2" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== dependencies: graceful-fs "^4.2.0" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^9.0.1: version "9.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc" integrity sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ== dependencies: at-least-node "^1.0.0" graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^1.0.0" fs-minipass@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== dependencies: minipass "^3.0.0" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== functional-red-black-tree@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= get-func-name@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41" integrity sha1-6td0q+5y4gQJQzoGY2YCPdaIekE= get-intrinsic@^1.0.2: version "1.2.0" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.0.tgz#7ad1dc0535f3a2904bba075772763e5051f6d05f" integrity sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q== dependencies: function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.3" get-own-enumerable-property-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203" integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg== get-stdin@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-7.0.0.tgz#8d5de98f15171a125c5e516643c7a6d0ea8a96f6" integrity sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ== get-stdin@~9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-9.0.0.tgz#3983ff82e03d56f1b2ea0d3e60325f39d703a575" integrity sha512-dVKBjfWisLAicarI2Sf+JuBE/DghV4UzNAVe9yhEJuzeREd3JhOTE9cUaJTeSa77fsbQUK3pcOpJfM59+VKZaA== get-stream@^5.0.0, get-stream@^5.1.0: version "5.2.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: pump "^3.0.0" getos@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/getos/-/getos-3.2.1.tgz#0134d1f4e00eb46144c5a9c0ac4dc087cbb27dc5" integrity sha512-U56CfOK17OKgTVqozZjUKNdkfEv6jk5WISBJ8SHoagjE6L69zOwl3Z+O8myjY9MEW3i2HPWQBt/LTbCgcC973Q== dependencies: async "^3.2.0" glob-parent@^5.0.0, glob-parent@^5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" glob-to-regexp@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== glob@^7.0.0, glob@^7.0.5, glob@^7.1.3, glob@^7.1.6: version "7.2.0" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" glob@~8.0.3: version "8.0.3" resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" integrity sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^5.0.1" once "^1.3.0" global-agent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/global-agent/-/global-agent-3.0.0.tgz#ae7cd31bd3583b93c5a16437a1afe27cc33a1ab6" integrity sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q== dependencies: boolean "^3.0.1" es6-error "^4.1.1" matcher "^3.0.0" roarr "^2.15.3" semver "^7.3.2" serialize-error "^7.0.1" globals@^12.1.0: version "12.4.0" resolved "https://registry.yarnpkg.com/globals/-/globals-12.4.0.tgz#a18813576a41b00a24a97e7f815918c2e19925f8" integrity sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg== dependencies: type-fest "^0.8.1" globalthis@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.3.tgz#5852882a52b80dc301b0660273e1ed082f0b6ccf" integrity sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA== dependencies: define-properties "^1.1.3" globby@^11.0.0, globby@^11.0.1: version "11.0.1" resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357" integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ== dependencies: array-union "^2.1.0" dir-glob "^3.0.1" fast-glob "^3.1.1" ignore "^5.1.4" merge2 "^1.3.0" slash "^3.0.0" got@^11.8.5: version "11.8.5" resolved "https://registry.yarnpkg.com/got/-/got-11.8.5.tgz#ce77d045136de56e8f024bebb82ea349bc730046" integrity sha512-o0Je4NvQObAuZPHLFoRSkdG2lTgtcynqymzg2Vupdx6PorhaT5MCbIyXG6d4D94kk8ZG57QeosgdiqfJWhEhlQ== dependencies: "@sindresorhus/is" "^4.0.0" "@szmarczak/http-timer" "^4.0.5" "@types/cacheable-request" "^6.0.1" "@types/responselike" "^1.0.0" cacheable-lookup "^5.0.3" cacheable-request "^7.0.2" decompress-response "^6.0.0" http2-wrapper "^1.0.0-beta.5.2" lowercase-keys "^2.0.0" p-cancelable "^2.0.0" responselike "^2.0.0" graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0, graceful-fs@^4.2.4, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== graceful-fs@~4.1.11: version "4.1.15" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA== has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== has-flag@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-5.0.1.tgz#5483db2ae02a472d1d0691462fc587d1843cd940" integrity sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA== has-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= has-symbols@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== has-symbols@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== dependencies: function-bind "^1.1.1" hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw== http-cache-semantics@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3" integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ== dependencies: depd "2.0.0" inherits "2.0.4" setprototypeof "1.2.0" statuses "2.0.1" toidentifier "1.0.1" http2-wrapper@^1.0.0-beta.5.2: version "1.0.3" resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-1.0.3.tgz#b8f55e0c1f25d4ebd08b3b0c2c079f9590800b3d" integrity sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg== dependencies: quick-lru "^5.1.1" resolve-alpn "^1.0.0" human-signals@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== husky@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.1.tgz#511cb3e57de3e3190514ae49ed50f6bc3f50b3e9" integrity sha512-xs7/chUH/CKdOCs7Zy0Aev9e/dKOMZf3K1Az1nar3tzlv0jfqnYtu235bstsWTmXOR0EfINrPa97yy4Lz6RiKw== [email protected], iconv-lite@^0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== ignore@^4.0.6: version "4.0.6" resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.0.0, ignore@^5.1.1, ignore@^5.1.4: version "5.1.8" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== ignore@~5.2.4: version "5.2.4" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== import-fresh@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.1.0.tgz#6d33fa1dcef6df930fae003446f33415af905118" integrity sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-fresh@^3.1.0: version "3.2.1" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66" integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-local@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg== dependencies: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" import-meta-resolve@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-1.1.1.tgz#244fd542fd1fae73550d4f8b3cde3bba1d7b2b18" integrity sha512-JiTuIvVyPaUg11eTrNDx5bgQ/yMKMZffc7YSjvQeSMXy58DO2SQ8BtAf3xteZvmzvjYh14wnqNjL8XVeDy2o9A== dependencies: builtins "^4.0.0" imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= indent-string@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2, [email protected], inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@^1.3.5: version "1.3.7" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.7.tgz#a09363e1911972ea16d7a8851005d84cf09a9a84" integrity sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ== ini@~3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/ini/-/ini-3.0.1.tgz#c76ec81007875bc44d544ff7a11a55d12294102d" integrity sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ== inquirer@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.3.0.tgz#aa3e7cb0c18a410c3c16cdd2bc9dcbe83c4d333e" integrity sha512-K+LZp6L/6eE5swqIcVXrxl21aGDU4S50gKH0/d96OMQnSBCyGyZl/oZhbkVmdp5sBoINHd4xZvFSARh2dk6DWA== dependencies: ansi-escapes "^4.2.1" chalk "^4.1.0" cli-cursor "^3.1.0" cli-width "^3.0.0" external-editor "^3.0.3" figures "^3.0.0" lodash "^4.17.15" mute-stream "0.0.8" run-async "^2.4.0" rxjs "^6.6.0" string-width "^4.1.0" strip-ansi "^6.0.0" through "^2.3.6" interpret@^1.0.0: version "1.4.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== interpret@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== [email protected]: version "1.9.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== is-alphabetical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-2.0.0.tgz#ef6e2caea57c63450fffc7abb6cbdafc5eb96e96" integrity sha512-5OV8Toyq3oh4eq6sbWTYzlGdnMT/DPI5I0zxUBxjiigQsZycpkKF3kskkao3JyYGuYDHvhgJF+DrjMQp9SX86w== is-alphanumerical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-2.0.0.tgz#0fbfeb6a72d21d91143b3d182bf6cf5909ee66f6" integrity sha512-t+2GlJ+hO9yagJ+jU3+HSh80VKvz/3cG2cxbGGm4S0hjKuhWQXgPVUVOZz3tqZzMjhmphZ+1TIJTlRZRoe6GCQ== dependencies: is-alphabetical "^2.0.0" is-decimal "^2.0.0" is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== dependencies: binary-extensions "^2.0.0" is-buffer@^2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== is-callable@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== is-callable@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.0.tgz#83336560b54a38e35e3a2df7afd0454d691468bb" integrity sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw== is-core-module@^2.8.0: version "2.8.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.1.tgz#f59fdfca701d5879d0a6b100a40aa1560ce27211" integrity sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA== dependencies: has "^1.0.3" is-core-module@^2.9.0: version "2.9.0" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== dependencies: has "^1.0.3" is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= is-decimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.0.tgz#db1140337809fd043a056ae40a9bd1cdc563034c" integrity sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw== is-empty@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" integrity sha1-3pu1snhzigWgsJpX4ftNSjQan2s= is-extglob@^2.1.0, is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== is-fullwidth-code-point@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== is-glob@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= dependencies: is-extglob "^2.1.0" is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-hexadecimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.0.tgz#8e1ec9f48fe3eabd90161109856a23e0907a65d5" integrity sha512-vGOtYkiaxwIiR0+Ng/zNId+ZZehGfINwTzdrDqc6iubbnQWhnPuYymOzOKUDqa2cSl59yHnEh2h6MvRLQsyNug== is-interactive@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== is-obj@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= is-plain-obj@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.0.0.tgz#06c0999fd7574edf5a906ba5644ad0feb3a84d22" integrity sha512-NXRbBtUdBioI73y/HmOhogw/U5msYPC9DAtGkJXeFcFWSFZw0mCUsPxk/snTuJHzNKA8kLBK4rH97RMB1BfCXw== is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-plain-object@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-4.1.1.tgz#1a14d6452cbd50790edc7fdaa0aed5a40a35ebb5" integrity sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA== is-plain-object@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== is-regex@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= dependencies: has "^1.0.1" is-regex@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.0.tgz#ece38e389e490df0dc21caea2bd596f987f767ff" integrity sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw== dependencies: has-symbols "^1.0.1" is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= is-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== is-string@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== is-symbol@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== dependencies: has-symbols "^1.0.0" isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= jest-worker@^27.4.5: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== dependencies: "@types/node" "*" merge-stream "^2.0.0" supports-color "^8.0.0" "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^3.13.1, js-yaml@^3.2.7: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== dependencies: argparse "^1.0.7" esprima "^4.0.0" js-yaml@^4.0.0, js-yaml@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== dependencies: argparse "^2.0.1" [email protected], json-buffer@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== json-parse-even-better-errors@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= json-stringify-safe@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== json5@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA== dependencies: minimist "^1.2.0" json5@^2.0.0, json5@^2.1.2: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== jsonc-parser@~3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= optionalDependencies: graceful-fs "^4.1.6" jsonfile@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.0.1.tgz#98966cba214378c8c84b82e085907b40bf614179" integrity sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg== dependencies: universalify "^1.0.0" optionalDependencies: graceful-fs "^4.1.6" jsonwebtoken@^9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz#d0faf9ba1cc3a56255fe49c0961a67e520c1926d" integrity sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw== dependencies: jws "^3.2.2" lodash "^4.17.21" ms "^2.1.1" semver "^7.3.8" jsx-ast-utils@^2.1.0: version "2.4.1" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz#1114a4c1209481db06c690c2b4f488cc665f657e" integrity sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w== dependencies: array-includes "^3.1.1" object.assign "^4.1.0" jwa@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a" integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA== dependencies: buffer-equal-constant-time "1.0.1" ecdsa-sig-formatter "1.0.11" safe-buffer "^5.0.1" jws@^3.2.2: version "3.2.2" resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304" integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA== dependencies: jwa "^1.4.1" safe-buffer "^5.0.1" keyv@^4.0.0: version "4.3.1" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.3.1.tgz#7970672f137d987945821b1a07b524ce5a4edd27" integrity sha512-nwP7AQOxFzELXsNq3zCx/oh81zu4DHWwCE6W9RaeHb7OHO0JpmKS8n801ovVQC7PTsZDWtPA5j1QY+/WWtARYg== dependencies: compress-brotli "^1.3.8" json-buffer "3.0.1" kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== klaw@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" integrity sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g== dependencies: graceful-fs "^4.1.9" kleur@^4.0.3: version "4.1.5" resolved "https://registry.yarnpkg.com/kleur/-/kleur-4.1.5.tgz#95106101795f7050c6c650f350c683febddb1780" integrity sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ== levn@^0.3.0, levn@~0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= dependencies: prelude-ls "~1.1.2" type-check "~0.3.2" levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== dependencies: prelude-ls "^1.2.1" type-check "~0.4.0" libnpmconfig@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/libnpmconfig/-/libnpmconfig-1.2.1.tgz#c0c2f793a74e67d4825e5039e7a02a0044dfcbc0" integrity sha512-9esX8rTQAHqarx6qeZqmGQKBNZR5OIbl/Ayr0qQDy3oXja2iFVQQI81R6GZ2a02bSNZ9p3YOGX1O6HHCb1X7kA== dependencies: figgy-pudding "^3.5.1" find-up "^3.0.0" ini "^1.3.5" lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= linkify-it@^3.0.1: version "3.0.3" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e" integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ== dependencies: uc.micro "^1.0.1" linkify-it@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-4.0.1.tgz#01f1d5e508190d06669982ba31a7d9f56a5751ec" integrity sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw== dependencies: uc.micro "^1.0.1" lint-staged@^10.2.11: version "10.2.11" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-10.2.11.tgz#713c80877f2dc8b609b05bc59020234e766c9720" integrity sha512-LRRrSogzbixYaZItE2APaS4l2eJMjjf5MbclRZpLJtcQJShcvUzKXsNeZgsLIZ0H0+fg2tL4B59fU9wHIHtFIA== dependencies: chalk "^4.0.0" cli-truncate "2.1.0" commander "^5.1.0" cosmiconfig "^6.0.0" debug "^4.1.1" dedent "^0.7.0" enquirer "^2.3.5" execa "^4.0.1" listr2 "^2.1.0" log-symbols "^4.0.0" micromatch "^4.0.2" normalize-path "^3.0.0" please-upgrade-node "^3.2.0" string-argv "0.3.1" stringify-object "^3.3.0" lint@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/lint/-/lint-1.1.2.tgz#35ed064f322547c331358d899868664968ba371f" integrity sha1-Ne0GTzIlR8MxNY2JmGhmSWi6Nx8= listr2@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/listr2/-/listr2-2.2.0.tgz#cb88631258abc578c7fb64e590fe5742f28e4aac" integrity sha512-Q8qbd7rgmEwDo1nSyHaWQeztfGsdL6rb4uh7BA+Q80AZiDET5rVntiU1+13mu2ZTDVaBVbvAD1Db11rnu3l9sg== dependencies: chalk "^4.0.0" cli-truncate "^2.1.0" figures "^3.2.0" indent-string "^4.0.0" log-update "^4.0.0" p-map "^4.0.0" rxjs "^6.5.5" through "^2.3.8" load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-2.0.0.tgz#7947e42149af80d696cbf797bcaabcfe1fe29ca8" integrity sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg= dependencies: graceful-fs "^4.1.2" parse-json "^2.2.0" pify "^2.0.0" strip-bom "^3.0.0" load-json-file@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-5.3.0.tgz#4d3c1e01fa1c03ea78a60ac7af932c9ce53403f3" integrity sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw== dependencies: graceful-fs "^4.1.15" parse-json "^4.0.0" pify "^4.0.1" strip-bom "^3.0.0" type-fest "^0.3.0" load-plugin@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/load-plugin/-/load-plugin-4.0.1.tgz#9a239b0337064c9b8aac82b0c9f89b067db487c5" integrity sha512-4kMi+mOSn/TR51pDo4tgxROHfBHXsrcyEYSGHcJ1o6TtRaP2PsRM5EwmYbj1uiLDvbfA/ohwuSWZJzqGiai8Dw== dependencies: import-meta-resolve "^1.0.0" libnpmconfig "^1.0.0" loader-runner@^4.2.0: version "4.3.0" resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== loader-utils@^1.0.2: version "1.4.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" integrity sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^1.0.1" loader-utils@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^2.1.2" locate-path@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" integrity sha1-K1aLJl7slExtnA3pw9u7ygNUzY4= dependencies: p-locate "^2.0.0" path-exists "^3.0.0" locate-path@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== dependencies: p-locate "^3.0.0" path-exists "^3.0.0" locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== dependencies: p-locate "^4.1.0" lodash.camelcase@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" integrity sha1-soqmKIorn8ZRA1x3EfZathkDMaY= lodash.flatten@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f" integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8= lodash.range@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/lodash.range/-/lodash.range-3.2.0.tgz#f461e588f66683f7eadeade513e38a69a565a15d" integrity sha1-9GHliPZmg/fq3q3lE+OKaaVloV0= lodash@^4.0.0, lodash@^4.17.11, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== dependencies: chalk "^2.0.1" log-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== dependencies: chalk "^2.4.2" log-symbols@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== dependencies: chalk "^4.0.0" log-update@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== dependencies: ansi-escapes "^4.3.0" cli-cursor "^3.1.0" slice-ansi "^4.0.0" wrap-ansi "^6.2.0" longest-streak@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-3.0.0.tgz#f127e2bded83caa6a35ac5f7a2f2b2f94b36f3dc" integrity sha512-XhUjWR5CFaQ03JOP+iSDS9koy8T5jfoImCZ4XprElw3BXsSk4MpVYOLw/6LTDKZhO13PlAXnB5gS4MHQTpkSOw== loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== dependencies: js-tokens "^3.0.0 || ^4.0.0" lowercase-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" make-error@^1.1.1: version "1.3.5" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== [email protected]: version "13.0.1" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-13.0.1.tgz#c6ecc431cacf1a5da531423fc6a42807814af430" integrity sha512-lTlxriVoy2criHP0JKRhO2VDG9c2ypWCsT237eDiLqi09rmbKoUetyGHq2uOIRoRS//kfoJckS0eUzzkDR+k2Q== dependencies: argparse "^2.0.1" entities "~3.0.1" linkify-it "^4.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdown-it@^12.0.0: version "12.3.2" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.3.2.tgz#bf92ac92283fe983fe4de8ff8abfb5ad72cd0c90" integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== dependencies: argparse "^2.0.1" entities "~2.1.0" linkify-it "^3.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdownlint-cli@^0.33.0: version "0.33.0" resolved "https://registry.yarnpkg.com/markdownlint-cli/-/markdownlint-cli-0.33.0.tgz#703af1234c32c309ab52fcd0e8bc797a34e2b096" integrity sha512-zMK1oHpjYkhjO+94+ngARiBBrRDEUMzooDHBAHtmEIJ9oYddd9l3chCReY2mPlecwH7gflQp1ApilTo+o0zopQ== dependencies: commander "~9.4.1" get-stdin "~9.0.0" glob "~8.0.3" ignore "~5.2.4" js-yaml "^4.1.0" jsonc-parser "~3.2.0" markdownlint "~0.27.0" minimatch "~5.1.2" run-con "~1.2.11" markdownlint@~0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.27.0.tgz#9dabf7710a4999e2835e3c68317f1acd0bc89049" integrity sha512-HtfVr/hzJJmE0C198F99JLaeada+646B5SaG2pVoEakLFI6iRGsvMqrnnrflq8hm1zQgwskEgqSnhDW11JBp0w== dependencies: markdown-it "13.0.1" matcher-collection@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/matcher-collection/-/matcher-collection-1.1.2.tgz#1076f506f10ca85897b53d14ef54f90a5c426838" integrity sha512-YQ/teqaOIIfUHedRam08PB3NK7Mjct6BvzRnJmpGDm8uFXpNr1sbY4yuflI5JcEs6COpYA0FpRQhSDBf1tT95g== dependencies: minimatch "^3.0.2" matcher@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca" integrity sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng== dependencies: escape-string-regexp "^4.0.0" mdast-comment-marker@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-comment-marker/-/mdast-comment-marker-1.1.1.tgz#9c9c18e1ed57feafc1965d92b028f37c3c8da70d" integrity sha512-TWZDaUtPLwKX1pzDIY48MkSUQRDwX/HqbTB4m3iYdL/zosi/Z6Xqfdv0C0hNVKvzrPjZENrpWDt4p4odeVO0Iw== mdast-util-from-markdown@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.0.tgz#c517313cd999ec2b8f6d447b438c5a9d500b89c9" integrity sha512-uj2G60sb7z1PNOeElFwCC9b/Se/lFXuLhVKFOAY2EHz/VvgbupTQRNXPoZl7rGpXYL6BNZgcgaybrlSWbo7n/g== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" mdast-util-to-string "^3.0.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" unist-util-stringify-position "^3.0.0" mdast-util-from-markdown@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.2.0.tgz#84df2924ccc6c995dec1e2368b2b208ad0a76268" integrity sha512-iZJyyvKD1+K7QX1b5jXdE7Sc5dtoTry1vzV28UZZe8Z1xVnB/czKntJ7ZAkG0tANqRnBF6p3p7GpU1y19DTf2Q== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" decode-named-character-reference "^1.0.0" mdast-util-to-string "^3.1.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-decode-string "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" unist-util-stringify-position "^3.0.0" uvu "^0.5.0" mdast-util-heading-style@^1.0.2: version "1.0.5" resolved "https://registry.yarnpkg.com/mdast-util-heading-style/-/mdast-util-heading-style-1.0.5.tgz#81b2e60d76754198687db0e8f044e42376db0426" integrity sha512-8zQkb3IUwiwOdUw6jIhnwM6DPyib+mgzQuHAe7j2Hy1rIarU4VUxe472bp9oktqULW3xqZE+Kz6OD4Gi7IA3vw== mdast-util-to-markdown@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-util-to-markdown/-/mdast-util-to-markdown-1.1.1.tgz#545ccc4dcc6672614b84fd1064482320dd689b12" integrity sha512-4puev/CxuxVdlsx5lVmuzgdqfjkkJJLS1Zm/MnejQ8I7BLeeBlbkwp6WOGJypEcN8g56LbVbhNmn84MvvcAvSQ== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" longest-streak "^3.0.0" mdast-util-to-string "^3.0.0" parse-entities "^3.0.0" zwitch "^2.0.0" mdast-util-to-string@^1.0.2: version "1.0.6" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-1.0.6.tgz#7d85421021343b33de1552fc71cb8e5b4ae7536d" integrity sha512-868pp48gUPmZIhfKrLbaDneuzGiw3OTDjHc5M1kAepR2CWBJ+HpEsm252K4aXdiP5coVZaJPOqGtVU6Po8xnXg== mdast-util-to-string@^3.0.0, mdast-util-to-string@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-3.1.0.tgz#56c506d065fbf769515235e577b5a261552d56e9" integrity sha512-n4Vypz/DZgwo0iMHLQL49dJzlp7YtAJP+N07MZHpjPf/5XJuHUWstviF4Mn2jEiR/GNmtnRRqnwsXExk3igfFA== mdurl@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= [email protected]: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g= memory-fs@^0.4.0: version "0.4.1" resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= dependencies: errno "^0.1.3" readable-stream "^2.0.1" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" integrity sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E= merge-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== merge2@^1.3.0: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== methods@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= micromark-core-commonmark@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-1.0.0.tgz#b767fa7687c205c224175bf067796360a3830350" integrity sha512-y9g7zymcKRBHM/aNBekstvs/Grpf+y4OEBULUTYvGZcusnp+JeOxmilJY4GMpo2/xY7iHQL9fjz5pD9pSAud9A== dependencies: micromark-factory-destination "^1.0.0" micromark-factory-label "^1.0.0" micromark-factory-space "^1.0.0" micromark-factory-title "^1.0.0" micromark-factory-whitespace "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-classify-character "^1.0.0" micromark-util-html-tag-name "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromark-factory-destination@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-destination/-/micromark-factory-destination-1.0.0.tgz#fef1cb59ad4997c496f887b6977aa3034a5a277e" integrity sha512-eUBA7Rs1/xtTVun9TmV3gjfPz2wEwgK5R5xcbIM5ZYAtvGF6JkyaDsj0agx8urXnO31tEO6Ug83iVH3tdedLnw== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-label@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz#b316ec479b474232973ff13b49b576f84a6f2cbb" integrity sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-space@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-space/-/micromark-factory-space-1.0.0.tgz#cebff49968f2b9616c0fcb239e96685cb9497633" integrity sha512-qUmqs4kj9a5yBnk3JMLyjtWYN6Mzfcx8uJfi5XAveBniDevmZasdGBba5b4QsvRcAkmvGo5ACmSUmyGiKTLZew== dependencies: micromark-util-character "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-title@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz#708f7a8044f34a898c0efdb4f55e4da66b537273" integrity sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-whitespace@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-whitespace/-/micromark-factory-whitespace-1.0.0.tgz#e991e043ad376c1ba52f4e49858ce0794678621c" integrity sha512-Qx7uEyahU1lt1RnsECBiuEbfr9INjQTGa6Err+gF3g0Tx4YEviPbqqGKNv/NrBaE7dVHdn1bVZKM/n5I/Bak7A== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-character@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/micromark-util-character/-/micromark-util-character-1.1.0.tgz#d97c54d5742a0d9611a68ca0cd4124331f264d86" integrity sha512-agJ5B3unGNJ9rJvADMJ5ZiYjBRyDpzKAOk01Kpi1TKhlT1APx3XZk6eN7RtSz1erbWHC2L8T3xLZ81wdtGRZzg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-chunked@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-chunked/-/micromark-util-chunked-1.0.0.tgz#5b40d83f3d53b84c4c6bce30ed4257e9a4c79d06" integrity sha512-5e8xTis5tEZKgesfbQMKRCyzvffRRUX+lK/y+DvsMFdabAicPkkZV6gO+FEWi9RfuKKoxxPwNL+dFF0SMImc1g== dependencies: micromark-util-symbol "^1.0.0" micromark-util-classify-character@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-classify-character/-/micromark-util-classify-character-1.0.0.tgz#cbd7b447cb79ee6997dd274a46fc4eb806460a20" integrity sha512-F8oW2KKrQRb3vS5ud5HIqBVkCqQi224Nm55o5wYLzY/9PwHGXC01tr3d7+TqHHz6zrKQ72Okwtvm/xQm6OVNZA== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-combine-extensions@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.0.0.tgz#91418e1e74fb893e3628b8d496085639124ff3d5" integrity sha512-J8H058vFBdo/6+AsjHp2NF7AJ02SZtWaVUjsayNFeAiydTxUwViQPxN0Hf8dp4FmCQi0UUFovFsEyRSUmFH3MA== dependencies: micromark-util-chunked "^1.0.0" micromark-util-types "^1.0.0" micromark-util-decode-numeric-character-reference@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.0.0.tgz#dcc85f13b5bd93ff8d2868c3dba28039d490b946" integrity sha512-OzO9AI5VUtrTD7KSdagf4MWgHMtET17Ua1fIpXTpuhclCqD8egFWo85GxSGvxgkGS74bEahvtM0WP0HjvV0e4w== dependencies: micromark-util-symbol "^1.0.0" micromark-util-decode-string@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/micromark-util-decode-string/-/micromark-util-decode-string-1.0.2.tgz#942252ab7a76dec2dbf089cc32505ee2bc3acf02" integrity sha512-DLT5Ho02qr6QWVNYbRZ3RYOSSWWFuH3tJexd3dgN1odEuPNxCngTCXJum7+ViRAd9BbdxCvMToPOD/IvVhzG6Q== dependencies: decode-named-character-reference "^1.0.0" micromark-util-character "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-encode@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-encode/-/micromark-util-encode-1.0.0.tgz#c409ecf751a28aa9564b599db35640fccec4c068" integrity sha512-cJpFVM768h6zkd8qJ1LNRrITfY4gwFt+tziPcIf71Ui8yFzY9wG3snZQqiWVq93PG4Sw6YOtcNiKJfVIs9qfGg== micromark-util-html-tag-name@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.0.0.tgz#75737e92fef50af0c6212bd309bc5cb8dbd489ed" integrity sha512-NenEKIshW2ZI/ERv9HtFNsrn3llSPZtY337LID/24WeLqMzeZhBEE6BQ0vS2ZBjshm5n40chKtJ3qjAbVV8S0g== micromark-util-normalize-identifier@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.0.0.tgz#4a3539cb8db954bbec5203952bfe8cedadae7828" integrity sha512-yg+zrL14bBTFrQ7n35CmByWUTFsgst5JhA4gJYoty4Dqzj4Z4Fr/DHekSS5aLfH9bdlfnSvKAWsAgJhIbogyBg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-resolve-all@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-resolve-all/-/micromark-util-resolve-all-1.0.0.tgz#a7c363f49a0162e931960c44f3127ab58f031d88" integrity sha512-CB/AGk98u50k42kvgaMM94wzBqozSzDDaonKU7P7jwQIuH2RU0TeBqGYJz2WY1UdihhjweivStrJ2JdkdEmcfw== dependencies: micromark-util-types "^1.0.0" micromark-util-sanitize-uri@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.0.0.tgz#27dc875397cd15102274c6c6da5585d34d4f12b2" integrity sha512-cCxvBKlmac4rxCGx6ejlIviRaMKZc0fWm5HdCHEeDWRSkn44l6NdYVRyU+0nT1XC72EQJMZV8IPHF+jTr56lAg== dependencies: micromark-util-character "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-subtokenize@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz#6f006fa719af92776c75a264daaede0fb3943c6a" integrity sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ== dependencies: micromark-util-chunked "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-symbol@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-symbol/-/micromark-util-symbol-1.0.0.tgz#91cdbcc9b2a827c0129a177d36241bcd3ccaa34d" integrity sha512-NZA01jHRNCt4KlOROn8/bGi6vvpEmlXld7EHcRH+aYWUfL3Wc8JLUNNlqUMKa0hhz6GrpUWsHtzPmKof57v0gQ== micromark-util-types@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-types/-/micromark-util-types-1.0.0.tgz#0ebdfaea3fa7c15fc82b1e06ea1ef0152d0fb2f0" integrity sha512-psf1WAaP1B77WpW4mBGDkTr+3RsPuDAgsvlP47GJzbH1jmjH8xjOx7Z6kp84L8oqHmy5pYO3Ev46odosZV+3AA== micromark@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/micromark/-/micromark-3.0.3.tgz#4c9f76fce8ba68eddf8730bb4fee2041d699d5b7" integrity sha512-fWuHx+JKV4zA8WfCFor2DWP9XmsZkIiyWRGofr7P7IGfpRIlb7/C5wwusGsNyr1D8HI5arghZDG1Ikc0FBwS5Q== dependencies: "@types/debug" "^4.0.0" debug "^4.0.0" micromark-core-commonmark "^1.0.0" micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-combine-extensions "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-sanitize-uri "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromatch@^4.0.0, micromatch@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259" integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q== dependencies: braces "^3.0.1" picomatch "^2.0.5" [email protected]: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== mime-types@^2.1.12, mime-types@^2.1.27, mime-types@~2.1.24, mime-types@~2.1.34: version "2.1.35" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== dependencies: mime-db "1.52.0" [email protected]: version "1.6.0" resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== mimic-fn@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== mimic-response@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== mimic-response@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.4: version "3.0.8" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.8.tgz#5e6a59bd11e2ab0de1cfb843eb2d82e546c321c1" integrity sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q== dependencies: brace-expansion "^1.1.7" minimatch@^5.0.1: version "5.1.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.1.tgz#6c9dffcf9927ff2a31e74b5af11adf8b9604b022" integrity sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g== dependencies: brace-expansion "^2.0.1" minimatch@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.2.tgz#0939d7d6f0898acbd1508abe534d1929368a8fff" integrity sha512-bNH9mmM9qsJ2X4r2Nat1B//1dJVcn3+iBLa3IgqJ7EbGaDNepL9QSHOxN4ng33s52VMMhhIfgCYDk3C4ZmlDAg== dependencies: brace-expansion "^2.0.1" minimist@^1.0.0, minimist@^1.2.5, minimist@^1.2.6, minimist@~1.2.0: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minimist@^1.2.0: version "1.2.7" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== minipass@^3.0.0: version "3.3.6" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw== dependencies: yallist "^4.0.0" minipass@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.1.tgz#2b9408c6e81bb8b338d600fb3685e375a370a057" integrity sha512-V9esFpNbK0arbN3fm2sxDKqMYgIp7XtVdE4Esj+PE4Qaaxdg1wIw48ITQIOn1sc8xXSmUviVL3cyjMqPlrVkiA== minizlib@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== dependencies: minipass "^3.0.0" yallist "^4.0.0" mkdirp@^0.5.1: version "0.5.5" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== dependencies: minimist "^1.2.5" mkdirp@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== mri@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= [email protected], ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== [email protected]: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== nan@nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac: version "2.15.0" resolved "https://codeload.github.com/nodejs/nan/tar.gz/16fa32231e2ccd89d2804b3f765319128b20c4ac" natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= [email protected]: version "0.6.3" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== neo-async@^2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-fetch@^2.6.1: version "2.6.8" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.8.tgz#a68d30b162bc1d8fd71a367e81b997e1f4d4937e" integrity sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg== dependencies: whatwg-url "^5.0.0" node-fetch@^2.6.7: version "2.6.7" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad" integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ== dependencies: whatwg-url "^5.0.0" node-releases@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503" integrity sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg== normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" resolve "^1.10.0" semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== normalize-url@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== npm-run-path@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: path-key "^3.0.0" null-loader@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-4.0.0.tgz#8e491b253cd87341d82c0e84b66980d806dfbd04" integrity sha512-vSoBF6M08/RHwc6r0gvB/xBJBtmbvvEkf6+IiadUCoNYchjxE8lwzCGFg0Qp2D25xPiJxUBh2iNWzlzGMILp7Q== dependencies: loader-utils "^2.0.0" schema-utils "^2.6.5" object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= object-inspect@^1.7.0: version "1.8.0" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.8.0.tgz#df807e5ecf53a609cc6bfe93eac3cc7be5b3a9d0" integrity sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA== object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g== object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object.assign@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== dependencies: define-properties "^1.1.2" function-bind "^1.1.1" has-symbols "^1.0.0" object-keys "^1.0.11" object.entries@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" has "^1.0.3" object.fromentries@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" integrity sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" object.values@^1.1.0, object.values@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.1.tgz#68a99ecde356b7e9295a3c5e0ce31dc8c953de5e" integrity sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" [email protected]: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== dependencies: ee-first "1.1.1" once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" onetime@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" integrity sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ= dependencies: mimic-fn "^1.0.0" onetime@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.0.tgz#fff0f3c91617fe62bb50189636e99ac8a6df7be5" integrity sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q== dependencies: mimic-fn "^2.1.0" optionator@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== dependencies: deep-is "~0.1.3" fast-levenshtein "~2.0.6" levn "~0.3.0" prelude-ls "~1.1.2" type-check "~0.3.2" word-wrap "~1.2.3" optionator@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== dependencies: deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" word-wrap "^1.2.3" ora@^3.4.0: version "3.4.0" resolved "https://registry.yarnpkg.com/ora/-/ora-3.4.0.tgz#bf0752491059a3ef3ed4c85097531de9fdbcd318" integrity sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg== dependencies: chalk "^2.4.2" cli-cursor "^2.1.0" cli-spinners "^2.0.0" log-symbols "^2.2.0" strip-ansi "^5.2.0" wcwidth "^1.0.1" ora@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.3.tgz#752a1b7b4be4825546a7a3d59256fa523b6b6d05" integrity sha512-fnDebVFyz309A73cqCipVL1fBZewq4vwgSHfxh43vVy31mbyoQ8sCH3Oeaog/owYOs/lLlGVPCISQonTneg6Pg== dependencies: chalk "^3.0.0" cli-cursor "^3.1.0" cli-spinners "^2.2.0" is-interactive "^1.0.0" log-symbols "^3.0.0" mute-stream "0.0.8" strip-ansi "^6.0.0" wcwidth "^1.0.1" os-tmpdir@^1.0.0, os-tmpdir@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= p-cancelable@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== p-limit@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8" integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q== dependencies: p-try "^1.0.0" p-limit@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2" integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ== dependencies: p-try "^2.0.0" p-limit@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" p-locate@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" integrity sha1-IKAQOyIqcMj9OcwuWAaA893l7EM= dependencies: p-limit "^1.1.0" p-locate@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== dependencies: p-limit "^2.0.0" p-locate@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== dependencies: p-limit "^2.2.0" p-map@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b" integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== dependencies: aggregate-error "^3.0.0" p-try@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3" integrity sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M= p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== parent-module@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== dependencies: callsites "^3.0.0" parse-entities@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-3.0.0.tgz#9ed6d6569b6cfc95ade058d683ddef239dad60dc" integrity sha512-AJlcIFDNPEP33KyJLguv0xJc83BNvjxwpuUIcetyXUsLpVXAUCePJ5kIoYtEN2R1ac0cYaRu/vk9dVFkewHQhQ== dependencies: character-entities "^2.0.0" character-entities-legacy "^2.0.0" character-reference-invalid "^2.0.0" is-alphanumerical "^2.0.0" is-decimal "^2.0.0" is-hexadecimal "^2.0.0" parse-gitignore@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/parse-gitignore/-/parse-gitignore-0.4.0.tgz#abf702e4b900524fff7902b683862857b63f93fe" integrity sha1-q/cC5LkAUk//eQK2g4YoV7Y/k/4= dependencies: array-unique "^0.3.2" is-glob "^3.1.0" parse-json@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= dependencies: error-ex "^1.2.0" parse-json@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= dependencies: error-ex "^1.3.1" json-parse-better-errors "^1.0.1" parse-json@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.0.0.tgz#73e5114c986d143efa3712d4ea24db9a4266f60f" integrity sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw== dependencies: "@babel/code-frame" "^7.0.0" error-ex "^1.3.1" json-parse-better-errors "^1.0.1" lines-and-columns "^1.1.6" parse-ms@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-key@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== path-parse@^1.0.6, path-parse@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== [email protected]: version "0.1.7" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w= path-type@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-2.0.0.tgz#f012ccb8415b7096fc2daa1054c3d72389594c73" integrity sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM= dependencies: pify "^2.0.0" path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== pathval@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pathval/-/pathval-1.1.1.tgz#8534e77a77ce7ac5a2512ea21e0fdb8fcf6c3d8d" integrity sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ== pend@~1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg== picocolors@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== picomatch@^2.0.4, picomatch@^2.0.5: version "2.0.7" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.0.7.tgz#514169d8c7cd0bdbeecc8a2609e34a7163de69f6" integrity sha512-oLHIdio3tZ0qH76NybpeneBhYVj0QFTfXEFTc/B3zKQspYfYYkWYgFsmzo+4kvId/bQRcNkVeguI3y+CD22BtA== picomatch@^2.2.1: version "2.2.2" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== picomatch@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== pify@^2.0.0: version "2.3.0" resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= pify@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== pkg-conf@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pkg-conf/-/pkg-conf-3.1.0.tgz#d9f9c75ea1bae0e77938cde045b276dac7cc69ae" integrity sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ== dependencies: find-up "^3.0.0" load-json-file "^5.2.0" pkg-config@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pkg-config/-/pkg-config-1.1.1.tgz#557ef22d73da3c8837107766c52eadabde298fe4" integrity sha1-VX7yLXPaPIg3EHdmxS6tq94pj+Q= dependencies: debug-log "^1.0.0" find-root "^1.0.0" xtend "^4.0.1" pkg-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-2.0.0.tgz#f6d5d1109e19d63edf428e0bd57e12777615334b" integrity sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s= dependencies: find-up "^2.1.0" pkg-dir@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== dependencies: find-up "^4.0.0" please-upgrade-node@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz#aeddd3f994c933e4ad98b99d9a556efa0e2fe942" integrity sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg== dependencies: semver-compare "^1.0.0" pluralize@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== pre-flight@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pre-flight/-/pre-flight-1.1.1.tgz#482fb1649fb400616a86b2706b11591f5cc8402d" integrity sha512-glqyc2Hh3K+sYeSsVs+HhjyUVf8j6xwuFej0yjYjRYfSnOK8P3Na9GznkoPn48fR+9kTOfkocYIWrtWktp4AqA== dependencies: colors "^1.1.2" commander "^2.9.0" semver "^5.1.0" prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== prelude-ls@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= pretty-ms@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.0.0.tgz#6133a8f55804b208e4728f6aa7bf01085e951e24" integrity sha512-94VRYjL9k33RzfKiGokPBPpsmloBYSf5Ri+Pq19zlsEcUKFob+admeXr5eFDRuPjFmEOcjJvPGdillYOJyvZ7Q== dependencies: parse-ms "^2.1.0" pretty-ms@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.1.0.tgz#b906bdd1ec9e9799995c372e2b1c34f073f95384" integrity sha512-4gaK1skD2gwscCfkswYQRmddUb2GJZtzDGRjHWadVHtK/DIKFufa12MvES6/xu1tVbUYeia5bmLcwJtZJQUqnw== dependencies: parse-ms "^2.1.0" process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== process@^0.11.10, process@~0.11.0: version "0.11.10" resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== progress@^2.0.0, progress@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== prop-types@^15.7.2: version "15.7.2" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== dependencies: loose-envify "^1.4.0" object-assign "^4.1.1" react-is "^16.8.1" proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= pump@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== dependencies: end-of-stream "^1.1.0" once "^1.3.1" [email protected]: version "1.3.2" resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" integrity sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw== punycode@^2.1.0: version "2.1.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== [email protected]: version "6.11.0" resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q== dependencies: side-channel "^1.0.4" [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g== quick-lru@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-5.1.1.tgz#366493e6b3e42a3a6885e2e99d18f80fb7a8c932" integrity sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA== ramda@^0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.27.0.tgz#915dc29865c0800bf3f69b8fd6c279898b59de43" integrity sha512-pVzZdDpWwWqEVVLshWUHjNwuVP7SfcmPraYuqocJp1yo2U1R7P+5QAfDhdItkuoGqIBnBYrtPp7rEPqDn9HlZA== randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== dependencies: safe-buffer "^5.1.0" range-parser@~1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== [email protected]: version "2.5.1" resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.1.tgz#fe1b1628b181b700215e5fd42389f98b71392857" integrity sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig== dependencies: bytes "3.1.2" http-errors "2.0.0" iconv-lite "0.4.24" unpipe "1.0.0" react-is@^16.8.1: version "16.8.6" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== read-pkg-up@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-2.0.0.tgz#6b72a8048984e0c41e79510fd5e9fa99b3b549be" integrity sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4= dependencies: find-up "^2.0.0" read-pkg "^2.0.0" read-pkg@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-2.0.0.tgz#8ef1c0623c6a6db0dc6713c4bfac46332b2368f8" integrity sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg= dependencies: load-json-file "^2.0.0" normalize-package-data "^2.3.2" path-type "^2.0.0" readable-stream@^2, readable-stream@^2.0.1, readable-stream@~2.3.6: version "2.3.6" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" isarray "~1.0.0" process-nextick-args "~2.0.0" safe-buffer "~5.1.1" string_decoder "~1.1.1" util-deprecate "~1.0.1" readable-stream@^3.0.2: version "3.6.0" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: inherits "^2.0.3" string_decoder "^1.1.1" util-deprecate "^1.0.1" readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== dependencies: picomatch "^2.2.1" rechoir@^0.6.2: version "0.6.2" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= dependencies: resolve "^1.1.6" rechoir@^0.7.0: version "0.7.1" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== dependencies: resolve "^1.9.0" regexpp@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-2.0.1.tgz#8d19d31cf632482b589049f8281f93dbcba4d07f" integrity sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw== regexpp@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.0.0.tgz#dd63982ee3300e67b41c1956f850aa680d9d330e" integrity sha512-Z+hNr7RAVWxznLPuA7DIh8UNX1j9CDrUQxskw9IrBE1Dxue2lyXT+shqEIeLUjrokxIP8CMy1WkjgG3rTsd5/g== regexpp@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== remark-cli@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-cli/-/remark-cli-10.0.0.tgz#3b0e20f2ad3909f35c7a6fb3f721c82f6ff5beac" integrity sha512-Yc5kLsJ5vgiQJl6xMLLJHqPac6OSAC5DOqKQrtmzJxSdJby2Jgr+OpIAkWQYwvbNHEspNagyoQnuwK2UCWg73g== dependencies: remark "^14.0.0" unified-args "^9.0.0" remark-lint-blockquote-indentation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-blockquote-indentation/-/remark-lint-blockquote-indentation-2.0.1.tgz#27347959acf42a6c3e401488d8210e973576b254" integrity sha512-uJ9az/Ms9AapnkWpLSCJfawBfnBI2Tn1yUsPNqIFv6YM98ymetItUMyP6ng9NFPqDvTQBbiarulkgoEo0wcafQ== dependencies: mdast-util-to-string "^1.0.2" pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-code-block-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-code-block-style/-/remark-lint-code-block-style-2.0.1.tgz#448b0f2660acfcdfff2138d125ff5b1c1279c0cb" integrity sha512-eRhmnColmSxJhO61GHZkvO67SpHDshVxs2j3+Zoc5Y1a4zQT2133ZAij04XKaBFfsVLjhbY/+YOWxgvtjx2nmA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-case@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-case/-/remark-lint-definition-case-2.0.1.tgz#10340eb2f87acff41140d52ad7e5b40b47e6690a" integrity sha512-M+XlThtQwEJLQnQb5Gi6xZdkw92rGp7m2ux58WMw/Qlcg02WgHR/O0OcHPe5VO5hMJrtI+cGG5T0svsCgRZd3w== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-spacing@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-spacing/-/remark-lint-definition-spacing-2.0.1.tgz#97f01bf9bf77a7bdf8013b124b7157dd90b07c64" integrity sha512-xK9DOQO5MudITD189VyUiMHBIKltW1oc55L7Fti3i9DedXoBG7Phm+V9Mm7IdWzCVkquZVgVk63xQdqzSQRrSQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-emphasis-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-emphasis-marker/-/remark-lint-emphasis-marker-2.0.1.tgz#1d5ca2070d4798d16c23120726158157796dc317" integrity sha512-7mpbAUrSnHiWRyGkbXRL5kfSKY9Cs8cdob7Fw+Z02/pufXMF4yRWaegJ5NTUu1RE+SKlF44wtWWjvcIoyY6/aw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-flag@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-flag/-/remark-lint-fenced-code-flag-2.0.1.tgz#2cb3ddb1157082c45760c7d01ca08e13376aaf62" integrity sha512-+COnWHlS/h02FMxoZWxNlZW3Y8M0cQQpmx3aNCbG7xkyMyCKsMLg9EmRvYHHIbxQCuF3JT0WWx5AySqlc7d+NA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-marker/-/remark-lint-fenced-code-marker-2.0.1.tgz#7bbeb0fb45b0818a3c8a2d232cf0c723ade58ecf" integrity sha512-lujpjm04enn3ma6lITlttadld6eQ1OWAEcT3qZzvFHp+zPraC0yr0eXlvtDN/0UH8mrln/QmGiZp3i8IdbucZg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-file-extension@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-file-extension/-/remark-lint-file-extension-1.0.3.tgz#a7fc78fbf041e513c618b2cca0f2160ee37daa13" integrity sha512-P5gzsxKmuAVPN7Kq1W0f8Ss0cFKfu+OlezYJWXf+5qOa+9Y5GqHEUOobPnsmNFZrVMiM7JoqJN2C9ZjrUx3N6Q== dependencies: unified-lint-rule "^1.0.0" remark-lint-final-definition@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/remark-lint-final-definition/-/remark-lint-final-definition-2.1.0.tgz#b6e654c01ebcb1afc936d7b9cd74db8ec273e0bb" integrity sha512-83K7n2icOHPfBzbR5Mr1o7cu8gOjD8FwJkFx/ly+rW+8SHfjCj4D3WOFGQ1xVdmHjfomBDXXDSNo2oiacADVXQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-hard-break-spaces@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-hard-break-spaces/-/remark-lint-hard-break-spaces-2.0.1.tgz#2149b55cda17604562d040c525a2a0d26aeb0f0f" integrity sha512-Qfn/BMQFamHhtbfLrL8Co/dbYJFLRL4PGVXZ5wumkUO5f9FkZC2RsV+MD9lisvGTkJK0ZEJrVVeaPbUIFM0OAw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-heading-increment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-increment/-/remark-lint-heading-increment-2.0.1.tgz#b578f251508a05d79bc2d1ae941e0620e23bf1d3" integrity sha512-bYDRmv/lk3nuWXs2VSD1B4FneGT6v7a74FuVmb305hyEMmFSnneJvVgnOJxyKlbNlz12pq1IQ6MhlJBda/SFtQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-heading-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-style/-/remark-lint-heading-style-2.0.1.tgz#8216fca67d97bbbeec8a19b6c71bfefc16549f72" integrity sha512-IrFLNs0M5Vbn9qg51AYhGUfzgLAcDOjh2hFGMz3mx664dV6zLcNZOPSdJBBJq3JQR4gKpoXcNwN1+FFaIATj+A== dependencies: mdast-util-heading-style "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-link-title-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-link-title-style/-/remark-lint-link-title-style-2.0.1.tgz#51a595c69fcfa73a245a030dfaa3504938a1173a" integrity sha512-+Q7Ew8qpOQzjqbDF6sUHmn9mKgje+m2Ho8Xz7cEnGIRaKJgtJzkn/dZqQM/az0gn3zaN6rOuwTwqw4EsT5EsIg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-list-item-content-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-content-indent/-/remark-lint-list-item-content-indent-2.0.1.tgz#96387459440dcd61e522ab02bff138b32bfaa63a" integrity sha512-OzUMqavxyptAdG7vWvBSMc9mLW9ZlTjbW4XGayzczd3KIr6Uwp3NEFXKx6MLtYIM/vwBqMrPQUrObOC7A2uBpQ== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-indent/-/remark-lint-list-item-indent-2.0.1.tgz#c6472514e17bc02136ca87936260407ada90bf8d" integrity sha512-4IKbA9GA14Q9PzKSQI6KEHU/UGO36CSQEjaDIhmb9UOhyhuzz4vWhnSIsxyI73n9nl9GGRAMNUSGzr4pQUFwTA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-spacing@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-list-item-spacing/-/remark-lint-list-item-spacing-3.0.0.tgz#14c18fe8c0f19231edb5cf94abda748bb773110b" integrity sha512-SRUVonwdN3GOSFb6oIYs4IfJxIVR+rD0nynkX66qEO49/qDDT1PPvkndis6Nyew5+t+2V/Db9vqllL6SWbnEtw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-maximum-heading-length@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-maximum-heading-length/-/remark-lint-maximum-heading-length-2.0.1.tgz#56f240707a75b59bce3384ccc9da94548affa98f" integrity sha512-1CjJ71YDqEpoOjUnc4wrwZV8ZGXWUIYRYeGoarAy3QKHepJL9M+zkdbOxZDfhc3tjVoDW/LWcgsW+DEpczgiMA== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-maximum-line-length@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/remark-lint-maximum-line-length/-/remark-lint-maximum-line-length-2.0.3.tgz#d0d15410637d61b031a83d7c78022ec46d6c858a" integrity sha512-zyWHBFh1oPAy+gkaVFXiTHYP2WwriIeBtaarDqkweytw0+qmuikjVMJTWbQ3+XfYBreD7KKDM9SI79nkp0/IZQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-auto-link-without-protocol@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-2.0.1.tgz#f75e5c24adb42385593e0d75ca39987edb70b6c4" integrity sha512-TFcXxzucsfBb/5uMqGF1rQA+WJJqm1ZlYQXyvJEXigEZ8EAxsxZGPb/gOQARHl/y0vymAuYxMTaChavPKaBqpQ== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-blockquote-without-marker@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-4.0.0.tgz#856fb64dd038fa8fc27928163caa24a30ff4d790" integrity sha512-Y59fMqdygRVFLk1gpx2Qhhaw5IKOR9T38Wf7pjR07bEFBGUNfcoNVIFMd1TCJfCPQxUyJzzSqfZz/KT7KdUuiQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-no-consecutive-blank-lines@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-consecutive-blank-lines/-/remark-lint-no-consecutive-blank-lines-3.0.0.tgz#c8fe11095b8f031a1406da273722bd4a9174bf41" integrity sha512-kmzLlOLrapBKEngwYFTdCZDmeOaze6adFPB7G0EdymD9V1mpAlnneINuOshRLEDKK5fAhXKiZXxdGIaMPkiXrA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-duplicate-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-duplicate-headings/-/remark-lint-no-duplicate-headings-2.0.1.tgz#4a4b70e029155ebcfc03d8b2358c427b69a87576" integrity sha512-F6AP0FJcHIlkmq0pHX0J5EGvLA9LfhuYTvnNO8y3kvflHeRjFkDyt2foz/taXR8OcLQR51n/jIJiwrrSMbiauw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-emphasis-as-heading@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-emphasis-as-heading/-/remark-lint-no-emphasis-as-heading-2.0.1.tgz#fcc064133fe00745943c334080fed822f72711ea" integrity sha512-z86+yWtVivtuGIxIC4g9RuATbgZgOgyLcnaleonJ7/HdGTYssjJNyqCJweaWSLoaI0akBQdDwmtJahW5iuX3/g== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-file-name-articles@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-articles/-/remark-lint-no-file-name-articles-1.0.3.tgz#c712d06a24e24b0c4c3666cf3084a0052a2c2c17" integrity sha512-YZDJDKUWZEmhrO6tHB0u0K0K2qJKxyg/kryr14OaRMvWLS62RgMn97sXPZ38XOSN7mOcCnl0k7/bClghJXx0sg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-consecutive-dashes@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-consecutive-dashes/-/remark-lint-no-file-name-consecutive-dashes-1.0.3.tgz#6a96ddf60e18dcdb004533733f3ccbfd8ab076ae" integrity sha512-7f4vyXn/ca5lAguWWC3eu5hi8oZ7etX7aQlnTSgQZeslnJCbVJm6V6prFJKAzrqbBzMicUXr5pZLBDoXyTvHHw== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-irregular-characters@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-irregular-characters/-/remark-lint-no-file-name-irregular-characters-1.0.3.tgz#6dcd8b51e00e10094585918cb8e7fc999df776c3" integrity sha512-b4xIy1Yi8qZpM2vnMN+6gEujagPGxUBAs1judv6xJQngkl5d5zT8VQZsYsTGHku4NWHjjh3b7vK5mr0/yp4JSg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-mixed-case@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-mixed-case/-/remark-lint-no-file-name-mixed-case-1.0.3.tgz#0ebe5eedd0191507d27ad6ac5eed1778cb33c2de" integrity sha512-d7rJ4c8CzDbEbGafw2lllOY8k7pvnsO77t8cV4PHFylwQ3hmCdTHLuDvK87G3DaWCeKclp0PMyamfOgJWKMkPA== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-outer-dashes@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-outer-dashes/-/remark-lint-no-file-name-outer-dashes-1.0.4.tgz#c6e22a5cc64df4e12fc31712a927e8039854a666" integrity sha512-+bZvvme2Bm3Vp5L2iKuvGHYVmHKrTkkRt8JqJPGepuhvBvT4Q7+CgfKyMtC/hIjyl+IcuJQ2H0qPRzdicjy1wQ== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-heading-punctuation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-heading-punctuation/-/remark-lint-no-heading-punctuation-2.0.1.tgz#face59f9a95c8aa278a8ee0c728bc44cd53ea9ed" integrity sha512-lY/eF6GbMeGu4cSuxfGHyvaQQBIq/6T/o+HvAR5UfxSTxmxZFwbZneAI2lbeR1zPcqOU87NsZ5ZZzWVwdLpPBw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-inline-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-inline-padding/-/remark-lint-no-inline-padding-3.0.0.tgz#14c2722bcddc648297a54298107a922171faf6eb" integrity sha512-3s9uW3Yux9RFC0xV81MQX3bsYs+UY7nPnRuMxeIxgcVwxQ4E/mTJd9QjXUwBhU9kdPtJ5AalngdmOW2Tgar8Cg== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-literal-urls@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-literal-urls/-/remark-lint-no-literal-urls-2.0.1.tgz#731908f9866c1880e6024dcee1269fb0f40335d6" integrity sha512-IDdKtWOMuKVQIlb1CnsgBoyoTcXU3LppelDFAIZePbRPySVHklTtuK57kacgU5grc7gPM04bZV96eliGrRU7Iw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-multiple-toplevel-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-multiple-toplevel-headings/-/remark-lint-no-multiple-toplevel-headings-2.0.1.tgz#3ff2b505adf720f4ff2ad2b1021f8cfd50ad8635" integrity sha512-VKSItR6c+u3OsE5pUiSmNusERNyQS9Nnji26ezoQ1uvy06k3RypIjmzQqJ/hCkSiF+hoyC3ibtrrGT8gorzCmQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-shell-dollars@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/remark-lint-no-shell-dollars/-/remark-lint-no-shell-dollars-2.0.2.tgz#b2c6c3ed95e5615f8e5f031c7d271a18dc17618e" integrity sha512-zhkHZOuyaD3r/TUUkkVqW0OxsR9fnSrAnHIF63nfJoAAUezPOu8D1NBsni6rX8H2DqGbPYkoeWrNsTwiKP0yow== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-image@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-image/-/remark-lint-no-shortcut-reference-image-2.0.1.tgz#d174d12a57e8307caf6232f61a795bc1d64afeaa" integrity sha512-2jcZBdnN6ecP7u87gkOVFrvICLXIU5OsdWbo160FvS/2v3qqqwF2e/n/e7D9Jd+KTq1mR1gEVVuTqkWWuh3cig== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-link@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-link/-/remark-lint-no-shortcut-reference-link-2.0.1.tgz#8f963f81036e45cfb7061b3639e9c6952308bc94" integrity sha512-pTZbslG412rrwwGQkIboA8wpBvcjmGFmvugIA+UQR+GfFysKtJ5OZMPGJ98/9CYWjw9Z5m0/EktplZ5TjFjqwA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-table-indentation@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-table-indentation/-/remark-lint-no-table-indentation-3.0.0.tgz#f3c3fc24375069ec8e510f43050600fb22436731" integrity sha512-+l7GovI6T+3LhnTtz/SmSRyOb6Fxy6tmaObKHrwb/GAebI/4MhFS1LVo3vbiP/RpPYtyQoFbbuXI55hqBG4ibQ== dependencies: unified-lint-rule "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-ordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-style/-/remark-lint-ordered-list-marker-style-2.0.1.tgz#183c31967e6f2ae8ef00effad03633f7fd00ffaa" integrity sha512-Cnpw1Dn9CHn+wBjlyf4qhPciiJroFOEGmyfX008sQ8uGoPZsoBVIJx76usnHklojSONbpjEDcJCjnOvfAcWW1A== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-ordered-list-marker-value@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-value/-/remark-lint-ordered-list-marker-value-2.0.1.tgz#0de343de2efb41f01eae9f0f7e7d30fe43db5595" integrity sha512-blt9rS7OKxZ2NW8tqojELeyNEwPhhTJGVa+YpUkdEH+KnrdcD7Nzhnj6zfLWOx6jFNZk3jpq5nvLFAPteHaNKg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-rule-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-rule-style/-/remark-lint-rule-style-2.0.1.tgz#f59bd82e75d3eaabd0eee1c8c0f5513372eb553c" integrity sha512-hz4Ff9UdlYmtO6Czz99WJavCjqCer7Cav4VopXt+yVIikObw96G5bAuLYcVS7hvMUGqC9ZuM02/Y/iq9n8pkAg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-strong-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-strong-marker/-/remark-lint-strong-marker-2.0.1.tgz#1ad8f190c6ac0f8138b638965ccf3bcd18f6d4e4" integrity sha512-8X2IsW1jZ5FmW9PLfQjkL0OVy/J3xdXLcZrG1GTeQKQ91BrPFyEZqUM2oM6Y4S6LGtxWer+neZkPZNroZoRPBQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-cell-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-cell-padding/-/remark-lint-table-cell-padding-3.0.0.tgz#a769ba1999984ff5f90294fb6ccb8aead7e8a12f" integrity sha512-sEKrbyFZPZpxI39R8/r+CwUrin9YtyRwVn0SQkNQEZWZcIpylK+bvoKIldvLIXQPob+ZxklL0GPVRzotQMwuWQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipe-alignment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-table-pipe-alignment/-/remark-lint-table-pipe-alignment-2.0.1.tgz#12b7e4c54473d69c9866cb33439c718d09cffcc5" integrity sha512-O89U7bp0ja6uQkT2uQrNB76GaPvFabrHiUGhqEUnld21yEdyj7rgS57kn84lZNSuuvN1Oor6bDyCwWQGzzpoOQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-pipes/-/remark-lint-table-pipes-3.0.0.tgz#b30b055d594cae782667eec91c6c5b35928ab259" integrity sha512-QPokSazEdl0Y8ayUV9UB0Ggn3Jos/RAQwIo0z1KDGnJlGDiF80Jc6iU9RgDNUOjlpQffSLIfSVxH5VVYF/K3uQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-unordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-unordered-list-marker-style/-/remark-lint-unordered-list-marker-style-2.0.1.tgz#e64692aa9594dbe7e945ae76ab2218949cd92477" integrity sha512-8KIDJNDtgbymEvl3LkrXgdxPMTOndcux3BHhNGB2lU4UnxSpYeHsxcDgirbgU6dqCAfQfvMjPvfYk19QTF9WZA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/remark-lint/-/remark-lint-8.0.0.tgz#6e40894f4a39eaea31fc4dd45abfaba948bf9a09" integrity sha512-ESI8qJQ/TIRjABDnqoFsTiZntu+FRifZ5fJ77yX63eIDijl/arvmDvT+tAf75/Nm5BFL4R2JFUtkHRGVjzYUsg== dependencies: remark-message-control "^6.0.0" remark-message-control@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/remark-message-control/-/remark-message-control-6.0.0.tgz#955b054b38c197c9f2e35b1d88a4912949db7fc5" integrity sha512-k9bt7BYc3G7YBdmeAhvd3VavrPa/XlKWR3CyHjr4sLO9xJyly8WHHT3Sp+8HPR8lEUv+/sZaffL7IjMLV0f6BA== dependencies: mdast-comment-marker "^1.0.0" unified-message-control "^3.0.0" remark-parse@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-parse/-/remark-parse-10.0.0.tgz#65e2b2b34d8581d36b97f12a2926bb2126961cb4" integrity sha512-07ei47p2Xl7Bqbn9H2VYQYirnAFJPwdMuypdozWsSbnmrkgA2e2sZLZdnDNrrsxR4onmIzH/J6KXqKxCuqHtPQ== dependencies: "@types/mdast" "^3.0.0" mdast-util-from-markdown "^1.0.0" unified "^10.0.0" remark-preset-lint-markdown-style-guide@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-preset-lint-markdown-style-guide/-/remark-preset-lint-markdown-style-guide-4.0.0.tgz#976b6ffd7f37aa90868e081a69241fcde3a297d4" integrity sha512-gczDlfZ28Fz0IN/oddy0AH4CiTu9S8d3pJWUsrnwFiafjhJjPGobGE1OD3bksi53md1Bp4K0fzo99YYfvB4Sjw== dependencies: remark-lint "^8.0.0" remark-lint-blockquote-indentation "^2.0.0" remark-lint-code-block-style "^2.0.0" remark-lint-definition-case "^2.0.0" remark-lint-definition-spacing "^2.0.0" remark-lint-emphasis-marker "^2.0.0" remark-lint-fenced-code-flag "^2.0.0" remark-lint-fenced-code-marker "^2.0.0" remark-lint-file-extension "^1.0.0" remark-lint-final-definition "^2.0.0" remark-lint-hard-break-spaces "^2.0.0" remark-lint-heading-increment "^2.0.0" remark-lint-heading-style "^2.0.0" remark-lint-link-title-style "^2.0.0" remark-lint-list-item-content-indent "^2.0.0" remark-lint-list-item-indent "^2.0.0" remark-lint-list-item-spacing "^3.0.0" remark-lint-maximum-heading-length "^2.0.0" remark-lint-maximum-line-length "^2.0.0" remark-lint-no-auto-link-without-protocol "^2.0.0" remark-lint-no-blockquote-without-marker "^4.0.0" remark-lint-no-consecutive-blank-lines "^3.0.0" remark-lint-no-duplicate-headings "^2.0.0" remark-lint-no-emphasis-as-heading "^2.0.0" remark-lint-no-file-name-articles "^1.0.0" remark-lint-no-file-name-consecutive-dashes "^1.0.0" remark-lint-no-file-name-irregular-characters "^1.0.0" remark-lint-no-file-name-mixed-case "^1.0.0" remark-lint-no-file-name-outer-dashes "^1.0.0" remark-lint-no-heading-punctuation "^2.0.0" remark-lint-no-inline-padding "^3.0.0" remark-lint-no-literal-urls "^2.0.0" remark-lint-no-multiple-toplevel-headings "^2.0.0" remark-lint-no-shell-dollars "^2.0.0" remark-lint-no-shortcut-reference-image "^2.0.0" remark-lint-no-shortcut-reference-link "^2.0.0" remark-lint-no-table-indentation "^3.0.0" remark-lint-ordered-list-marker-style "^2.0.0" remark-lint-ordered-list-marker-value "^2.0.0" remark-lint-rule-style "^2.0.0" remark-lint-strong-marker "^2.0.0" remark-lint-table-cell-padding "^3.0.0" remark-lint-table-pipe-alignment "^2.0.0" remark-lint-table-pipes "^3.0.0" remark-lint-unordered-list-marker-style "^2.0.0" remark-stringify@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-10.0.0.tgz#7f23659d92b2d5da489e3c858656d7bbe045f161" integrity sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA== dependencies: "@types/mdast" "^3.0.0" mdast-util-to-markdown "^1.0.0" unified "^10.0.0" remark@^14.0.0: version "14.0.1" resolved "https://registry.yarnpkg.com/remark/-/remark-14.0.1.tgz#a97280d4f2a3010a7d81e6c292a310dcd5554d80" integrity sha512-7zLG3u8EUjOGuaAS9gUNJPD2j+SqDqAFHv2g6WMpE5CU9rZ6e3IKDM12KHZ3x+YNje+NMAuN55yx8S5msGSx7Q== dependencies: "@types/mdast" "^3.0.0" remark-parse "^10.0.0" remark-stringify "^10.0.0" unified "^10.0.0" repeat-string@^1.0.0: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= requireindex@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.1.0.tgz#e5404b81557ef75db6e49c5a72004893fe03e162" integrity sha1-5UBLgVV+91225JxacgBIk/4D4WI= resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" integrity sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g== resolve-cwd@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== dependencies: resolve-from "^5.0.0" resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== resolve-from@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== resolve@^1.1.6: version "1.21.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.21.0.tgz#b51adc97f3472e6a5cf4444d34bc9d6b9037591f" integrity sha512-3wCbTpk5WJlyE4mSOtDLhqQmGFi0/TD9VPwmiolnk8U0wRgMEktqCXd3vy5buTO3tljvalNvKrjHEfrd2WpEKA== dependencies: is-core-module "^2.8.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" resolve@^1.10.0: version "1.11.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e" integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw== dependencies: path-parse "^1.0.6" resolve@^1.10.1, resolve@^1.11.0, resolve@^1.13.1, resolve@^1.17.0: version "1.17.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== dependencies: path-parse "^1.0.6" resolve@^1.9.0: version "1.22.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177" integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw== dependencies: is-core-module "^2.9.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" responselike@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/responselike/-/responselike-2.0.0.tgz#26391bcc3174f750f9a79eacc40a12a5c42d7723" integrity sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw== dependencies: lowercase-keys "^2.0.0" restore-cursor@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" integrity sha1-n37ih/gv0ybU/RYpI9YhKe7g368= dependencies: onetime "^2.0.0" signal-exit "^3.0.2" restore-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== dependencies: onetime "^5.1.0" signal-exit "^3.0.2" reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== [email protected]: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== dependencies: glob "^7.1.3" rimraf@~2.2.6: version "2.2.8" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.8.tgz#e439be2aaee327321952730f99a8929e4fc50582" integrity sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI= roarr@^2.15.3: version "2.15.4" resolved "https://registry.yarnpkg.com/roarr/-/roarr-2.15.4.tgz#f5fe795b7b838ccfe35dc608e0282b9eba2e7afd" integrity sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A== dependencies: boolean "^3.0.1" detect-node "^2.0.4" globalthis "^1.0.1" json-stringify-safe "^5.0.1" semver-compare "^1.0.0" sprintf-js "^1.1.2" run-async@^2.4.0: version "2.4.1" resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" integrity sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ== run-con@~1.2.11: version "1.2.11" resolved "https://registry.yarnpkg.com/run-con/-/run-con-1.2.11.tgz#0014ed430bad034a60568dfe7de2235f32e3f3c4" integrity sha512-NEMGsUT+cglWkzEr4IFK21P4Jca45HqiAbIIZIBdX5+UZTB24Mb/21iNGgz9xZa8tL6vbW7CXmq7MFN42+VjNQ== dependencies: deep-extend "^0.6.0" ini "~3.0.0" minimist "^1.2.6" strip-json-comments "~3.1.1" run-parallel@^1.1.2, run-parallel@^1.1.9: version "1.1.9" resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679" integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q== rxjs@^6.5.5, rxjs@^6.6.0: version "6.6.0" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.6.0.tgz#af2901eedf02e3a83ffa7f886240ff9018bbec84" integrity sha512-3HMA8z/Oz61DUHe+SdOiQyzIf4tOx5oQHmMir7IZEu6TMqCLHT4LRcmNaUS0NwOz8VLvmmBduMsoaUvMaIiqzg== dependencies: tslib "^1.9.0" sade@^1.7.3: version "1.8.1" resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701" integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A== dependencies: mri "^1.1.0" [email protected], safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== "safer-buffer@>= 2.1.2 < 3": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== sax@>=0.6.0: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== schema-utils@^2.6.5: version "2.7.0" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.7.0.tgz#17151f76d8eae67fbbf77960c33c676ad9f4efc7" integrity sha512-0ilKFI6QQF5nxDZLFn2dMjvc4hjg/Wkg7rHd3jK6/A4a1Hl9VFdQWvgB1UMGoU94pad1P/8N7fMcEnLnSiju8A== dependencies: "@types/json-schema" "^7.0.4" ajv "^6.12.2" ajv-keywords "^3.4.1" schema-utils@^3.1.0, schema-utils@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-3.1.1.tgz#bc74c4b6b6995c1d88f76a8b77bea7219e0c8281" integrity sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw== dependencies: "@types/json-schema" "^7.0.8" ajv "^6.12.5" ajv-keywords "^3.5.2" semver-compare@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= "semver@2 || 3 || 4 || 5", semver@^5.6.0: version "5.7.0" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b" integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA== semver@^5.1.0, semver@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db" integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A== semver@^6.1.0, semver@^6.1.2, semver@^6.2.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== semver@^7.0.0: version "7.3.5" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7" integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== dependencies: lru-cache "^6.0.0" semver@^7.2.1, semver@^7.3.2: version "7.3.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938" integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ== semver@^7.3.5, semver@^7.3.8: version "7.3.8" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== dependencies: lru-cache "^6.0.0" [email protected]: version "0.18.0" resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be" integrity sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg== dependencies: debug "2.6.9" depd "2.0.0" destroy "1.2.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" fresh "0.5.2" http-errors "2.0.0" mime "1.6.0" ms "2.1.3" on-finished "2.4.1" range-parser "~1.2.1" statuses "2.0.1" serialize-error@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/serialize-error/-/serialize-error-7.0.1.tgz#f1360b0447f61ffb483ec4157c737fab7d778e18" integrity sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw== dependencies: type-fest "^0.13.1" serialize-javascript@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== dependencies: randombytes "^2.1.0" [email protected]: version "1.15.0" resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.15.0.tgz#faaef08cffe0a1a62f60cad0c4e513cff0ac9540" integrity sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g== dependencies: encodeurl "~1.0.2" escape-html "~1.0.3" parseurl "~1.3.3" send "0.18.0" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== shallow-clone@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== dependencies: kind-of "^6.0.2" shebang-command@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= dependencies: shebang-regex "^1.0.0" shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== dependencies: shebang-regex "^3.0.0" shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= shebang-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== shelljs@^0.8.1: version "0.8.5" resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.8.5.tgz#de055408d8361bed66c669d2f000538ced8ee20c" integrity sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow== dependencies: glob "^7.0.0" interpret "^1.0.0" rechoir "^0.6.2" shx@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/shx/-/shx-0.3.2.tgz#40501ce14eb5e0cbcac7ddbd4b325563aad8c123" integrity sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA== dependencies: es6-object-assign "^1.0.3" minimist "^1.2.0" shelljs "^0.8.1" side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== dependencies: call-bind "^1.0.0" get-intrinsic "^1.0.2" object-inspect "^1.9.0" signal-exit@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== simple-git@^3.5.0: version "3.16.0" resolved "https://registry.yarnpkg.com/simple-git/-/simple-git-3.16.0.tgz#421773e24680f5716999cc4a1d60127b4b6a9dec" integrity sha512-zuWYsOLEhbJRWVxpjdiXl6eyAyGo/KzVW+KFhhw9MqEEJttcq+32jTWSGyxTdf9e/YCohxRE+9xpWFj9FdiJNw== dependencies: "@kwsites/file-exists" "^1.1.1" "@kwsites/promise-deferred" "^1.1.1" debug "^4.3.4" slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== slice-ansi@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-2.1.0.tgz#cacd7693461a637a5788d92a7dd4fba068e81636" integrity sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ== dependencies: ansi-styles "^3.2.0" astral-regex "^1.0.0" is-fullwidth-code-point "^2.0.0" slice-ansi@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" slice-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" sliced@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/sliced/-/sliced-1.0.1.tgz#0b3a662b5d04c3177b1926bea82b03f837a2ef41" integrity sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E= source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map@^0.6.0: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== spdx-correct@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== spdx-expression-parse@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: version "3.0.4" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz#75ecd1a88de8c184ef015eafb51b5b48bfd11bb1" integrity sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA== sprintf-js@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.2.tgz#da1765262bf8c0f571749f2ad6c26300207ae673" integrity sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug== sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= standard-engine@^12.0.0: version "12.1.0" resolved "https://registry.yarnpkg.com/standard-engine/-/standard-engine-12.1.0.tgz#b13dbae583de54c06805207b991ef48a582c0e62" integrity sha512-DVJnWM1CGkag4ucFLGdiYWa5/kJURPONmMmk17p8FT5NE4UnPZB1vxWnXnRo2sPSL78pWJG8xEM+1Tu19z0deg== dependencies: deglob "^4.0.1" get-stdin "^7.0.0" minimist "^1.2.5" pkg-conf "^3.1.0" standard-markdown@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/standard-markdown/-/standard-markdown-6.0.0.tgz#bb7519a86275900eaa7a951d98937723c7010ed6" integrity sha512-9lQs4ZfGukyalFVputnN4IxfbMIAECjf+BqC4gvY8eBUvYcotYIWj4MZyMiXBkN/OJwmMi5jVSnzIexKZQqQYA== dependencies: commander "^4.1.0" globby "^11.0.0" lodash.flatten "^4.4.0" lodash.range "^3.2.0" ora "^4.0.3" standard "^14.3.1" standard@^14.3.1: version "14.3.4" resolved "https://registry.yarnpkg.com/standard/-/standard-14.3.4.tgz#748e80e8cd7b535844a85a12f337755a7e3a0f6e" integrity sha512-+lpOkFssMkljJ6eaILmqxHQ2n4csuEABmcubLTb9almFi1ElDzXb1819fjf/5ygSyePCq4kU2wMdb2fBfb9P9Q== dependencies: eslint "~6.8.0" eslint-config-standard "14.1.1" eslint-config-standard-jsx "8.1.0" eslint-plugin-import "~2.18.0" eslint-plugin-node "~10.0.0" eslint-plugin-promise "~4.2.1" eslint-plugin-react "~7.14.2" eslint-plugin-standard "~4.0.0" standard-engine "^12.0.0" [email protected]: version "2.0.1" resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== stream-chain@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/stream-chain/-/stream-chain-2.2.3.tgz#44cfa21ab673e53a3f1691b3d1665c3aceb1983b" integrity sha512-w+WgmCZ6BItPAD3/4HD1eDiDHRLhjSSyIV+F0kcmmRyz8Uv9hvQF22KyaiAUmOlmX3pJ6F95h+C191UbS8Oe/g== stream-json@^1.7.1: version "1.7.1" resolved "https://registry.yarnpkg.com/stream-json/-/stream-json-1.7.1.tgz#ec7e414c2eba456c89a4b4e5223794eabc3860c4" integrity sha512-I7g0IDqvdJXbJ279/D3ZoTx0VMhmKnEF7u38CffeWdF8bfpMPsLo+5fWnkNjO2GU/JjWaRjdH+zmH03q+XGXFw== dependencies: stream-chain "^2.2.3" [email protected]: version "0.3.1" resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== string-width@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== dependencies: emoji-regex "^7.0.1" is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" string-width@^4.1.0, string-width@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== dependencies: emoji-regex "^8.0.0" is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" string-width@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.0.0.tgz#19191f152f937b96f4ec54ba0986a5656660c5a2" integrity sha512-zwXcRmLUdiWhMPrHz6EXITuyTgcEnUqDzspTkCLhQovxywWz6NP9VHgqfVg20V/1mUg0B95AKbXxNT+ALRmqCw== dependencies: emoji-regex "^9.2.2" is-fullwidth-code-point "^4.0.0" strip-ansi "^7.0.0" string.prototype.trimend@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz#85812a6b847ac002270f5808146064c995fb6913" integrity sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string.prototype.trimstart@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz#14af6d9f34b053f7cfc89b72f8f2ee14b9039a54" integrity sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string_decoder@^1.1.1: version "1.3.0" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== dependencies: safe-buffer "~5.2.0" string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" stringify-object@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== dependencies: get-own-enumerable-property-symbols "^3.0.0" is-obj "^1.0.1" is-regexp "^1.0.0" strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== dependencies: ansi-regex "^4.1.0" strip-ansi@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== dependencies: ansi-regex "^5.0.0" strip-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.0.tgz#1dc49b980c3a4100366617adac59327eefdefcb0" integrity sha512-UhDTSnGF1dc0DRbUqr1aXwNoY3RgVkSWG8BrpnuFIxhP57IqbS7IRta2Gfiavds4yCxc5+fEAVVOgBZWnYkvzg== dependencies: ansi-regex "^6.0.0" strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= strip-final-newline@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== strip-json-comments@^3.0.1, strip-json-comments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.0.tgz#7638d31422129ecf4457440009fba03f9f9ac180" integrity sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w== strip-json-comments@~3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== sumchecker@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/sumchecker/-/sumchecker-3.0.1.tgz#6377e996795abb0b6d348e9b3e1dfb24345a8e42" integrity sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg== dependencies: debug "^4.1.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" supports-color@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.1.0.tgz#68e32591df73e25ad1c4b49108a2ec507962bfd1" integrity sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g== dependencies: has-flag "^4.0.0" supports-color@^8.0.0: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== dependencies: has-flag "^4.0.0" supports-color@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.0.2.tgz#50f082888e4b0a4e2ccd2d0b4f9ef4efcd332485" integrity sha512-ii6tc8ImGFrgMPYq7RVAMKkhPo9vk8uA+D3oKbJq/3Pk2YSMv1+9dUAesa9UxMbxBTvxwKTQffBahNVNxEvM8Q== dependencies: has-flag "^5.0.0" supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== table@^5.2.3: version "5.4.6" resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e" integrity sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug== dependencies: ajv "^6.10.2" lodash "^4.17.14" slice-ansi "^2.1.0" string-width "^3.0.0" tap-parser@~1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-1.2.2.tgz#5e2f6970611f079c7cf857de1dc7aa1b480de7a5" integrity sha1-Xi9pcGEfB5x8+FfeHceqG0gN56U= dependencies: events-to-array "^1.0.1" inherits "~2.0.1" js-yaml "^3.2.7" optionalDependencies: readable-stream "^2" tap-xunit@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/tap-xunit/-/tap-xunit-2.4.1.tgz#9823797b676ae5017f4e380bd70abb893b8e120e" integrity sha512-qcZStDtjjYjMKAo7QNiCtOW256g3tuSyCSe5kNJniG1Q2oeOExJq4vm8CwboHZURpkXAHvtqMl4TVL7mcbMVVA== dependencies: duplexer "~0.1.1" minimist "~1.2.0" tap-parser "~1.2.2" through2 "~2.0.0" xmlbuilder "~4.2.0" xtend "~4.0.0" tapable@^1.0.0: version "1.1.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== tapable@^2.1.1, tapable@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== tar@^6.1.11: version "6.1.13" resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b" integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw== dependencies: chownr "^2.0.0" fs-minipass "^2.0.0" minipass "^4.0.0" minizlib "^2.1.1" mkdirp "^1.0.3" yallist "^4.0.0" temp@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/temp/-/temp-0.8.3.tgz#e0c6bc4d26b903124410e4fed81103014dfc1f59" integrity sha1-4Ma8TSa5AxJEEOT+2BEDAU38H1k= dependencies: os-tmpdir "^1.0.0" rimraf "~2.2.6" terser-webpack-plugin@^5.1.3: version "5.3.3" resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.3.tgz#8033db876dd5875487213e87c627bca323e5ed90" integrity sha512-Fx60G5HNYknNTNQnzQ1VePRuu89ZVYWfjRAeT5rITuCY/1b08s49e5kSQwHDirKZWuoKOBRFS98EUUoZ9kLEwQ== dependencies: "@jridgewell/trace-mapping" "^0.3.7" jest-worker "^27.4.5" schema-utils "^3.1.1" serialize-javascript "^6.0.0" terser "^5.7.2" terser@^5.7.2: version "5.14.2" resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== dependencies: "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" commander "^2.20.0" source-map-support "~0.5.20" text-table@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= through2@~2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== dependencies: readable-stream "~2.3.6" xtend "~4.0.1" through@^2.3.6, through@^2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= [email protected]: version "1.4.2" resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.4.2.tgz#c9c58b575be8407375cb5e2462dacee74359f41d" integrity sha1-ycWLV1voQHN1y14kYtrO50NZ9B0= dependencies: process "~0.11.0" tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== dependencies: is-number "^7.0.0" to-vfile@^7.0.0: version "7.2.1" resolved "https://registry.yarnpkg.com/to-vfile/-/to-vfile-7.2.1.tgz#fe42892024f724177ba81076f98ee74b0888c293" integrity sha512-biljADNq2n+AZn/zX+/87zStnIqctKr/q5OaOD8+qSKINokUGPbWBShvxa1iLUgHz6dGGjVnQPNoFRtVBzMkVg== dependencies: is-buffer "^2.0.0" vfile "^5.0.0" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= trough@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/trough/-/trough-2.0.2.tgz#94a3aa9d5ce379fc561f6244905b3f36b7458d96" integrity sha512-FnHq5sTMxC0sk957wHDzRnemFnNBvt/gSY99HzK8F7UP5WAbvP70yX5bd7CjEQkN+TjdxwI7g7lJ6podqrG2/w== ts-loader@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-8.0.2.tgz#ee73ca9350f745799396fff8578ba29b1e95616b" integrity sha512-oYT7wOTUawYXQ8XIDsRhziyW0KUEV38jISYlE+9adP6tDtG+O5GkRe4QKQXrHVH4mJJ88DysvEtvGP65wMLlhg== dependencies: chalk "^2.3.0" enhanced-resolve "^4.0.0" loader-utils "^1.0.2" micromatch "^4.0.0" semver "^6.0.0" [email protected]: version "6.2.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-6.2.0.tgz#65a0ae2acce319ea4fd7ac8d7c9f1f90c5da6baf" integrity sha512-ZNT+OEGfUNVMGkpIaDJJ44Zq3Yr0bkU/ugN1PHbU+/01Z7UV1fsELRiTx1KuQNvQ1A3pGh3y25iYF6jXgxV21A== dependencies: arrify "^1.0.0" buffer-from "^1.1.0" diff "^3.1.0" make-error "^1.1.1" minimist "^1.2.0" mkdirp "^0.5.1" source-map-support "^0.5.6" yn "^2.0.0" tsconfig-paths@^3.9.0: version "3.9.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz#098547a6c4448807e8fcb8eae081064ee9a3c90b" integrity sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw== dependencies: "@types/json5" "^0.0.29" json5 "^1.0.1" minimist "^1.2.0" strip-bom "^3.0.0" tslib@^1.8.1, tslib@^1.9.0: version "1.10.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== tslib@^2.0.0, tslib@^2.2.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== dependencies: tslib "^1.8.1" tunnel@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== dependencies: prelude-ls "^1.2.1" type-check@~0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= dependencies: prelude-ls "~1.1.2" type-detect@^4.0.0, type-detect@^4.0.5: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== type-fest@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.11.0.tgz#97abf0872310fed88a5c466b25681576145e33f1" integrity sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ== type-fest@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934" integrity sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg== type-fest@^0.3.0: version "0.3.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ== type-fest@^0.8.1: version "0.8.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== type-is@~1.6.18: version "1.6.18" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== dependencies: media-typer "0.3.0" mime-types "~2.1.24" typedarray@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= typescript@^4.5.5: version "4.5.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== unified-args@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/unified-args/-/unified-args-9.0.2.tgz#0c14f555e73ee29c23f9a567942e29069f56e5a2" integrity sha512-qSqryjoqfJSII4E4Z2Jx7MhXX2MuUIn6DsrlmL8UnWFdGtrWvEtvm7Rx5fKT5TPUz7q/Fb4oxwIHLCttvAuRLQ== dependencies: "@types/text-table" "^0.2.0" camelcase "^6.0.0" chalk "^4.0.0" chokidar "^3.0.0" fault "^2.0.0" json5 "^2.0.0" minimist "^1.0.0" text-table "^0.2.0" unified-engine "^9.0.0" unified-engine@^9.0.0: version "9.0.3" resolved "https://registry.yarnpkg.com/unified-engine/-/unified-engine-9.0.3.tgz#c1d57e67d94f234296cbfa9364f43e0696dae016" integrity sha512-SgzREcCM2IpUy3JMFUcPRZQ2Py6IwvJ2KIrg2AiI7LnGge6E6OPFWpcabHrEXG0IvO2OI3afiD9DOcQvvZfXDQ== dependencies: "@types/concat-stream" "^1.0.0" "@types/debug" "^4.0.0" "@types/is-empty" "^1.0.0" "@types/js-yaml" "^4.0.0" "@types/node" "^16.0.0" "@types/unist" "^2.0.0" concat-stream "^2.0.0" debug "^4.0.0" fault "^2.0.0" glob "^7.0.0" ignore "^5.0.0" is-buffer "^2.0.0" is-empty "^1.0.0" is-plain-obj "^4.0.0" js-yaml "^4.0.0" load-plugin "^4.0.0" parse-json "^5.0.0" to-vfile "^7.0.0" trough "^2.0.0" unist-util-inspect "^7.0.0" vfile-message "^3.0.0" vfile-reporter "^7.0.0" vfile-statistics "^2.0.0" unified-lint-rule@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/unified-lint-rule/-/unified-lint-rule-1.0.4.tgz#be432d316db7ad801166041727b023ba18963e24" integrity sha512-q9wY6S+d38xRAuWQVOMjBQYi7zGyKkY23ciNafB8JFVmDroyKjtytXHCg94JnhBCXrNqpfojo3+8D+gmF4zxJQ== dependencies: wrapped "^1.0.1" unified-message-control@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unified-message-control/-/unified-message-control-3.0.3.tgz#d08c4564092a507668de71451a33c0d80e734bbd" integrity sha512-oY5z2n8ugjpNHXOmcgrw0pQeJzavHS0VjPBP21tOcm7rc2C+5Q+kW9j5+gqtf8vfW/8sabbsK5+P+9QPwwEHDA== dependencies: unist-util-visit "^2.0.0" vfile-location "^3.0.0" unified@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/unified/-/unified-10.1.0.tgz#4e65eb38fc2448b1c5ee573a472340f52b9346fe" integrity sha512-4U3ru/BRXYYhKbwXV6lU6bufLikoAavTwev89H5UxY8enDFaAT2VXmIXYNm6hb5oHPng/EXr77PVyDFcptbk5g== dependencies: "@types/unist" "^2.0.0" bail "^2.0.0" extend "^3.0.0" is-buffer "^2.0.0" is-plain-obj "^4.0.0" trough "^2.0.0" vfile "^5.0.0" uniq@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" integrity sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8= unist-util-generated@^1.0.0: version "1.1.6" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.6.tgz#5ab51f689e2992a472beb1b35f2ce7ff2f324d4b" integrity sha512-cln2Mm1/CZzN5ttGK7vkoGw+RZ8VcUH6BtGbq98DDtRGquAAOXig1mrBQYelOwMXYS8rK+vZDyyojSjp7JX+Lg== unist-util-generated@^1.1.0: version "1.1.4" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.4.tgz#2261c033d9fc23fae41872cdb7663746e972c1a7" integrity sha512-SA7Sys3h3X4AlVnxHdvN/qYdr4R38HzihoEVY2Q2BZu8NHWDnw5OGcC/tXWjQfd4iG+M6qRFNIRGqJmp2ez4Ww== unist-util-inspect@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/unist-util-inspect/-/unist-util-inspect-7.0.0.tgz#98426f0219e24d011a27e32539be0693d9eb973e" integrity sha512-2Utgv78I7PUu461Y9cdo+IUiiKSKpDV5CE/XD6vTj849a3xlpDAScvSJ6cQmtFBGgAmCn2wR7jLuXhpg1XLlJw== dependencies: "@types/unist" "^2.0.0" unist-util-is@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-4.1.0.tgz#976e5f462a7a5de73d94b706bac1b90671b57797" integrity sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg== unist-util-is@^5.0.0: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-5.1.1.tgz#e8aece0b102fa9bc097b0fef8f870c496d4a6236" integrity sha512-F5CZ68eYzuSvJjGhCLPL3cYx45IxkqXSetCcRgUXtbcm50X2L9oOWQlfUfDdAf+6Pd27YDblBfdtmsThXmwpbQ== unist-util-position@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unist-util-position/-/unist-util-position-3.0.3.tgz#fff942b879538b242096c148153826664b1ca373" integrity sha512-28EpCBYFvnMeq9y/4w6pbnFmCUfzlsc41NJui5c51hOFjBA1fejcwc+5W4z2+0ECVbScG3dURS3JTVqwenzqZw== unist-util-stringify-position@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-2.0.1.tgz#de2a2bc8d3febfa606652673a91455b6a36fb9f3" integrity sha512-Zqlf6+FRI39Bah8Q6ZnNGrEHUhwJOkHde2MHVk96lLyftfJJckaPslKgzhVcviXj8KcE9UJM9F+a4JEiBUTYgA== dependencies: "@types/unist" "^2.0.2" unist-util-stringify-position@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-3.0.0.tgz#d517d2883d74d0daa0b565adc3d10a02b4a8cde9" integrity sha512-SdfAl8fsDclywZpfMDTVDxA2V7LjtRDTOFd44wUJamgl6OlVngsqWjxvermMYf60elWHbxhuRCZml7AnuXCaSA== dependencies: "@types/unist" "^2.0.0" unist-util-visit-parents@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz#65a6ce698f78a6b0f56aa0e88f13801886cdaef6" integrity sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-5.1.1.tgz#868f353e6fce6bf8fa875b251b0f4fec3be709bb" integrity sha512-gks4baapT/kNRaWxuGkl5BIhoanZo7sC/cUT/JToSRNL1dYoXRFl75d++NkjYk4TAu2uv2Px+l8guMajogeuiw== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-2.0.3.tgz#c3703893146df47203bb8a9795af47d7b971208c" integrity sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents "^3.0.0" unist-util-visit@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.1.tgz#1c4842d70bd3df6cc545276f5164f933390a9aad" integrity sha512-n9KN3WV9k4h1DxYR1LoajgN93wpEi/7ZplVe02IoB4gH5ctI1AaF2670BLHQYbwj+pY83gFtyeySFiyMHJklrg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit-parents "^5.1.1" universal-github-app-jwt@^1.0.1: version "1.1.1" resolved "https://registry.yarnpkg.com/universal-github-app-jwt/-/universal-github-app-jwt-1.1.1.tgz#d57cee49020662a95ca750a057e758a1a7190e6e" integrity sha512-G33RTLrIBMFmlDV4u4CBF7dh71eWwykck4XgaxaIVeZKOYZRAAxvcGMRFTUclVY6xoUPQvO4Ne5wKGxYm/Yy9w== dependencies: "@types/jsonwebtoken" "^9.0.0" jsonwebtoken "^9.0.0" universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== universalify@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== universalify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d" integrity sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug== universalify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== [email protected], unpipe@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" integrity sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw= update-browserslist-db@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38" integrity sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q== dependencies: escalade "^3.1.1" picocolors "^1.0.0" uri-js@^4.2.2: version "4.4.1" resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== dependencies: punycode "^2.1.0" url@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1" integrity sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ== dependencies: punycode "1.3.2" querystring "0.2.0" util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM= uuid@^8.3.0: version "8.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== uvu@^0.5.0: version "0.5.6" resolved "https://registry.yarnpkg.com/uvu/-/uvu-0.5.6.tgz#2754ca20bcb0bb59b64e9985e84d2e81058502df" integrity sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA== dependencies: dequal "^2.0.0" diff "^5.0.0" kleur "^4.0.3" sade "^1.7.3" v8-compile-cache@^2.0.3: version "2.1.1" resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745" integrity sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ== validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" vary@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw= vfile-location@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-3.2.0.tgz#d8e41fbcbd406063669ebf6c33d56ae8721d0f3c" integrity sha512-aLEIZKv/oxuCDZ8lkJGhuhztf/BW4M+iHdCwglA/eWc+vtuRFJj8EtgceYFX4LRjOhCAAiNHsKGssC6onJ+jbA== vfile-message@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.0.1.tgz#b9bcf87cb5525e61777e0c6df07e816a577588a3" integrity sha512-gYmSHcZZUEtYpTmaWaFJwsuUD70/rTY4v09COp8TGtOkix6gGxb/a8iTQByIY9ciTk9GwAwIXd/J9OPfM4Bvaw== dependencies: "@types/unist" "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-reporter@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.1.tgz#759bfebb995f3dc8c644284cb88ac4b310ebd168" integrity sha512-pof+cQSJCUNmHG6zoBOJfErb6syIWHWM14CwKjsugCixxl4CZdrgzgxwLBW8lIB6czkzX0Agnnhj33YpKyLvmA== dependencies: "@types/repeat-string" "^1.0.0" "@types/supports-color" "^8.0.0" repeat-string "^1.0.0" string-width "^5.0.0" supports-color "^9.0.0" unist-util-stringify-position "^3.0.0" vfile-sort "^3.0.0" vfile-statistics "^2.0.0" vfile-sort@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/vfile-sort/-/vfile-sort-3.0.0.tgz#ee13d3eaac0446200a2047a3b45d78fad6b106e6" integrity sha512-fJNctnuMi3l4ikTVcKpxTbzHeCgvDhnI44amA3NVDvA6rTC6oKCFpCVyT5n2fFMr3ebfr+WVQZedOCd73rzSxg== dependencies: vfile-message "^3.0.0" vfile-statistics@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/vfile-statistics/-/vfile-statistics-2.0.0.tgz#f04ee3e3c666809a3c10c06021becd41ea9c8037" integrity sha512-foOWtcnJhKN9M2+20AOTlWi2dxNfAoeNIoxD5GXcO182UJyId4QrXa41fWrgcfV3FWTjdEDy3I4cpLVcQscIMA== dependencies: vfile-message "^3.0.0" vfile@^5.0.0: version "5.0.2" resolved "https://registry.yarnpkg.com/vfile/-/vfile-5.0.2.tgz#57773d1d91478b027632c23afab58ec3590344f0" integrity sha512-5cV+K7tX83MT3bievROc+7AvHv0GXDB0zqbrTjbOe+HRbkzvY4EP+wS3IR77kUBCoWFMdG9py18t0sesPtQ1Rw== dependencies: "@types/unist" "^2.0.0" is-buffer "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" [email protected]: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz#f239ed2cd6004021b6550af9fd9d3e47eee3cac9" integrity sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ== [email protected]: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz#beaa46aea06ed061576586c5e11368a9afc1d378" integrity sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg== dependencies: vscode-jsonrpc "8.0.2" vscode-languageserver-types "3.17.2" vscode-languageserver-textdocument@^1.0.5, vscode-languageserver-textdocument@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz#16df468d5c2606103c90554ae05f9f3d335b771b" integrity sha512-bFJH7UQxlXT8kKeyiyu41r22jCZXG8kuuVVA33OEJn1diWOZK5n8zBSPZFHVBOu8kXZ6h0LIRhf5UnCo61J4Hg== [email protected], vscode-languageserver-types@^3.17.1: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz#b2c2e7de405ad3d73a883e91989b850170ffc4f2" integrity sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA== vscode-languageserver@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.0.2.tgz#cfe2f0996d9dfd40d3854e786b2821604dfec06d" integrity sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA== dependencies: vscode-languageserver-protocol "3.17.2" vscode-uri@^3.0.3, vscode-uri@^3.0.6: version "3.0.6" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.6.tgz#5e6e2e1a4170543af30151b561a41f71db1d6f91" integrity sha512-fmL7V1eiDBFRRnu+gfRWTzyPpNIHJTc4mWnFkwBUmO9U3KPgJAmTx7oxi2bl/Rh6HLdU7+4C9wlj0k2E4AdKFQ== walk-sync@^0.3.2: version "0.3.4" resolved "https://registry.yarnpkg.com/walk-sync/-/walk-sync-0.3.4.tgz#cf78486cc567d3a96b5b2237c6108017a5ffb9a4" integrity sha512-ttGcuHA/OBnN2pcM6johpYlEms7XpO5/fyKIr48541xXedan4roO8cS1Q2S/zbbjGH/BarYDAMeS2Mi9HE5Tig== dependencies: ensure-posix-path "^1.0.0" matcher-collection "^1.0.0" watchpack@^2.4.0: version "2.4.0" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" integrity sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g= dependencies: defaults "^1.0.3" webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE= webpack-cli@^4.10.0: version "4.10.0" resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== dependencies: "@discoveryjs/json-ext" "^0.5.0" "@webpack-cli/configtest" "^1.2.0" "@webpack-cli/info" "^1.5.0" "@webpack-cli/serve" "^1.7.0" colorette "^2.0.14" commander "^7.0.0" cross-spawn "^7.0.3" fastest-levenshtein "^1.0.12" import-local "^3.0.2" interpret "^2.2.0" rechoir "^0.7.0" webpack-merge "^5.7.3" webpack-merge@^5.7.3: version "5.8.0" resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" integrity sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q== dependencies: clone-deep "^4.0.1" wildcard "^2.0.0" webpack-sources@^3.2.3: version "3.2.3" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== webpack@^5, webpack@^5.76.0: version "5.76.0" resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.76.0.tgz#f9fb9fb8c4a7dbdcd0d56a98e56b8a942ee2692c" integrity sha512-l5sOdYBDunyf72HW8dF23rFtWq/7Zgvt/9ftMof71E/yUb1YLOBmTgA2K4vQthB3kotMrSj609txVE0dnr2fjA== dependencies: "@types/eslint-scope" "^3.7.3" "@types/estree" "^0.0.51" "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/wasm-edit" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" acorn "^8.7.1" acorn-import-assertions "^1.7.6" browserslist "^4.14.5" chrome-trace-event "^1.0.2" enhanced-resolve "^5.10.0" es-module-lexer "^0.9.0" eslint-scope "5.1.1" events "^3.2.0" glob-to-regexp "^0.4.1" graceful-fs "^4.2.9" json-parse-even-better-errors "^2.3.1" loader-runner "^4.2.0" mime-types "^2.1.27" neo-async "^2.6.2" schema-utils "^3.1.0" tapable "^2.1.1" terser-webpack-plugin "^5.1.3" watchpack "^2.4.0" webpack-sources "^3.2.3" whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" integrity sha1-lmRU6HZUYuN2RNNib2dCzotwll0= dependencies: tr46 "~0.0.3" webidl-conversions "^3.0.0" which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" which@^2.0.1: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" wildcard@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== word-wrap@^1.2.3, word-wrap@~1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== wrap-ansi@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== dependencies: ansi-styles "^4.0.0" string-width "^4.1.0" strip-ansi "^6.0.0" wrapped@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wrapped/-/wrapped-1.0.1.tgz#c783d9d807b273e9b01e851680a938c87c907242" integrity sha1-x4PZ2Aeyc+mwHoUWgKk4yHyQckI= dependencies: co "3.1.0" sliced "^1.0.1" wrapper-webpack-plugin@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/wrapper-webpack-plugin/-/wrapper-webpack-plugin-2.2.2.tgz#a950b7fbc39ca103e468a7c06c225cb1e337ad3b" integrity sha512-twLGZw0b2AEnz3LmsM/uCFRzGxE+XUlUPlJkCuHY3sI+uGO4dTJsgYee3ufWJaynAZYkpgQSKMSr49n9Yxalzg== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= [email protected]: version "1.0.3" resolved "https://registry.yarnpkg.com/write/-/write-1.0.3.tgz#0800e14523b923a387e415123c865616aae0f5c3" integrity sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig== dependencies: mkdirp "^0.5.1" xml2js@^0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.5.0.tgz#d9440631fbb2ed800203fad106f2724f62c493b7" integrity sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA== dependencies: sax ">=0.6.0" xmlbuilder "~11.0.0" xmlbuilder@~11.0.0: version "11.0.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== xmlbuilder@~4.2.0: version "4.2.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5" integrity sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU= dependencies: lodash "^4.0.0" xtend@^4.0.1, xtend@~4.0.0, xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== yallist@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== yaml@^1.7.2: version "1.10.0" resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9" integrity sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g== dependencies: buffer-crc32 "~0.2.3" fd-slicer "~1.1.0" yn@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/yn/-/yn-2.0.0.tgz#e5adabc8acf408f6385fc76495684c88e6af689a" integrity sha1-5a2ryKz0CPY4X8dklWhMiOavaJo= zwitch@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.2.tgz#91f8d0e901ffa3d66599756dde7f57b17c95dce1" integrity sha512-JZxotl7SxAJH0j7dN4pxsTV6ZLXoLdGME+PsjkL/DaBrVryK9kTGq06GfKrwcSOqypP+fdXGoCHE36b99fWVoA==
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "base/mac/scoped_nsobject.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_.get(); } ElectronTouchBar* touch_bar() const { return touch_bar_.get(); } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_; base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); w.setKiosk(true); await setTimeout(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "base/mac/scoped_nsobject.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_.get(); } ElectronTouchBar* touch_bar() const { return touch_bar_.get(); } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_; base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,204
[Feature Request]: Stay in fullscreen when leaving Kiosk mode
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description My issue is the same as described here: https://github.com/electron/electron/issues/8338#issue-198786856. The merged fix from 2017 appears to not have made it to the newer versions of Electron. Toggling kiosk mode to false forces an Electron app out of fullscreen, which is not the desired behavior. ### Proposed Solution I'd like to reinstate the merged change from 2017, preserving fullscreen on disabling Kiosk mode. ### Alternatives Considered No alternatives considered, as `setKiosk` is the only way to toggle kiosk mode. ### Additional Information _No response_
https://github.com/electron/electron/issues/38204
https://github.com/electron/electron/pull/38219
f432245456e92fe0191ae0b9275fdee60dd45452
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2023-05-06T20:26:19Z
c++
2023-05-09T16:28:37Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); w.setKiosk(true); await setTimeout(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,215
[Bug]: The `devtools-open-url` event has an incorrect type in typescript
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 22H2 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior The `devtools-open-url` event handler is actually called with the following args: `(e: Electron.Event, url: string)`. The typescript code for it should also reflect that. ### Actual Behavior The typescript code for this event in electron.d.ts looks like this: ```d.ts on(event: 'devtools-open-url', listener: ( /** * URL of the link that was clicked or selected. */ url: string) => void): this; // ... same for once, addListener, removeListener ``` Which does not have the `Event` parameter. The code that actually works (without a runtime error) throws this error in typescript: ``` No overload matches this call. The last overload gave the following error. Argument of type '"devtools-open-url"' is not assignable to parameter of type '"zoom-changed"'. ts(2769) ``` And, obviously, if you follow the typescript rules, you're going to get an `Electron.Event` object instead of the expected `string` one. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38215
https://github.com/electron/electron/pull/38231
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2806feede2cf5264b0187dddfdd7fc6cca915fbf
2023-05-08T22:27:14Z
c++
2023-05-10T09:25:50Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Navigation Events Several events can be used to monitor navigations as they occur within a `webContents`. ### Document Navigations When a `webContents` navigates to another page (as opposed to an [in-page navigation](web-contents.md#in-page-navigation)), the following events will be fired. * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) * [`will-navigate`](web-contents.md#event-will-navigate) (only fired when main frame navigates) * [`will-redirect`](web-contents.md#event-will-redirect) (only fired when a redirect happens during navigation) * [`did-redirect-navigation`](web-contents.md#event-did-redirect-navigation) (only fired when a redirect happens during navigation) * [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) * [`did-navigate`](web-contents.md#event-did-navigate) (only fired when main frame navigates) Subsequent events will not fire if `event.preventDefault()` is called on any of the cancellable events. ### In-page Navigation In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order: * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`did-navigate-in-page`](web-contents.md#event-did-navigate-in-page) ### Frame Navigation The [`will-navigate`](web-contents.md#event-will-navigate) and [`did-navigate`](web-contents.md#event-did-navigate) events only fire when the [mainFrame](web-contents.md#contentsmainframe-readonly) navigates. If you want to also observe navigations in `<iframe>`s, use [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) and [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) events. ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents | null` - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents | undefined` - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents | undefined` - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents | undefined` - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'content-bounds-updated' Returns: * `event` Event * `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs. By default, this will move the window. To prevent that behavior, call `event.preventDefault()`. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md) - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window` or `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when a user or the page wants to start navigation on the main frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'will-frame-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. Emitted when a user or the page wants to start navigation in any frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. Unlike `will-navigate`, `will-frame-navigate` is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, `isMainFrame` will be `true`. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when a bluetooth device needs to be selected when a call to `navigator.bluetooth.requestDevice` is made. `callback` should be called with the `deviceId` of the device to be selected. Passing an empty string to `callback` will cancel the request. If an event listener is not added for this event, or if `event.preventDefault` is not called when handling this event, the first available device will be automatically selected. Due to the nature of bluetooth, scanning for devices when `navigator.bluetooth.requestDevice` is called may take time and will cause `select-bluetooth-device` to fire multiple times until `callback` is called with either a device id or an empty string to cancel the request. ```javascript title='main.js' const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or cancel the request by calling the callback // with an empty string. callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` [WebPreferences](structures/web-preferences.md) - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` [IpcMainEvent](structures/ipc-main-event.md) * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` [IpcMainEvent](structures/ipc-main-event.md) * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.centerSelection()` Centers the current text selection in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.scrollToTop()` Scrolls to the top of the current `webContents`. #### `contents.scrollToBottom()` Scrolls to the bottom of the current `webContents`. #### `contents.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. Example: ```js const win = new BrowserWindow() // Adjusts the beginning of the selection 1 letter forward, // and the end of the selection 5 letters forward. win.webContents.adjustSelection({ start: 1, end: 5 }) // Adjusts the beginning of the selection 2 letters forward, // and the end of the selection 3 letters backward. win.webContents.adjustSelection({ start: 2, end: -3 }) ``` For a call of `win.webContents.adjustSelection({ start: 1, end: 5 })` Before: <img width="487" alt="Image Before Text Selection Adjustment" src="https://user-images.githubusercontent.com/2036040/231761306-cd4e7b15-c2ed-46cf-8e80-10811f6de83e.png"> After: <img width="487" alt="Image After Text Selection Adjustment" src="https://user-images.githubusercontent.com/2036040/231761169-887eb8ef-06fb-46e4-9efa-898bcb0d6a2b.png"> #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`](#contentsfindinpagetext-options) request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js title='main.js' const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | \[number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether _offscreen rendering_ is enabled. #### `contents.startPainting()` If _offscreen rendering_ is enabled and not painting, start painting. #### `contents.stopPainting()` If _offscreen rendering_ is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If _offscreen rendering_ is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If _offscreen rendering_ is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If _offscreen rendering_ is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If _offscreen rendering_ is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if _offscreen rendering_ is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
38,215
[Bug]: The `devtools-open-url` event has an incorrect type in typescript
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 22H2 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior The `devtools-open-url` event handler is actually called with the following args: `(e: Electron.Event, url: string)`. The typescript code for it should also reflect that. ### Actual Behavior The typescript code for this event in electron.d.ts looks like this: ```d.ts on(event: 'devtools-open-url', listener: ( /** * URL of the link that was clicked or selected. */ url: string) => void): this; // ... same for once, addListener, removeListener ``` Which does not have the `Event` parameter. The code that actually works (without a runtime error) throws this error in typescript: ``` No overload matches this call. The last overload gave the following error. Argument of type '"devtools-open-url"' is not assignable to parameter of type '"zoom-changed"'. ts(2769) ``` And, obviously, if you follow the typescript rules, you're going to get an `Electron.Event` object instead of the expected `string` one. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38215
https://github.com/electron/electron/pull/38231
13e309e1fb2491af7c4bfd6bc6e786dbeb8dfc4b
2806feede2cf5264b0187dddfdd7fc6cca915fbf
2023-05-08T22:27:14Z
c++
2023-05-10T09:25:50Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Navigation Events Several events can be used to monitor navigations as they occur within a `webContents`. ### Document Navigations When a `webContents` navigates to another page (as opposed to an [in-page navigation](web-contents.md#in-page-navigation)), the following events will be fired. * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) * [`will-navigate`](web-contents.md#event-will-navigate) (only fired when main frame navigates) * [`will-redirect`](web-contents.md#event-will-redirect) (only fired when a redirect happens during navigation) * [`did-redirect-navigation`](web-contents.md#event-did-redirect-navigation) (only fired when a redirect happens during navigation) * [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) * [`did-navigate`](web-contents.md#event-did-navigate) (only fired when main frame navigates) Subsequent events will not fire if `event.preventDefault()` is called on any of the cancellable events. ### In-page Navigation In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order: * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`did-navigate-in-page`](web-contents.md#event-did-navigate-in-page) ### Frame Navigation The [`will-navigate`](web-contents.md#event-will-navigate) and [`did-navigate`](web-contents.md#event-did-navigate) events only fire when the [mainFrame](web-contents.md#contentsmainframe-readonly) navigates. If you want to also observe navigations in `<iframe>`s, use [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) and [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) events. ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents | null` - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents | undefined` - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents | undefined` - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents | undefined` - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'content-bounds-updated' Returns: * `event` Event * `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs. By default, this will move the window. To prevent that behavior, call `event.preventDefault()`. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md) - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window` or `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when a user or the page wants to start navigation on the main frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'will-frame-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. Emitted when a user or the page wants to start navigation in any frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. Unlike `will-navigate`, `will-frame-navigate` is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, `isMainFrame` will be `true`. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when a bluetooth device needs to be selected when a call to `navigator.bluetooth.requestDevice` is made. `callback` should be called with the `deviceId` of the device to be selected. Passing an empty string to `callback` will cancel the request. If an event listener is not added for this event, or if `event.preventDefault` is not called when handling this event, the first available device will be automatically selected. Due to the nature of bluetooth, scanning for devices when `navigator.bluetooth.requestDevice` is called may take time and will cause `select-bluetooth-device` to fire multiple times until `callback` is called with either a device id or an empty string to cancel the request. ```javascript title='main.js' const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or cancel the request by calling the callback // with an empty string. callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` [WebPreferences](structures/web-preferences.md) - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` [IpcMainEvent](structures/ipc-main-event.md) * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` [IpcMainEvent](structures/ipc-main-event.md) * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.centerSelection()` Centers the current text selection in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.scrollToTop()` Scrolls to the top of the current `webContents`. #### `contents.scrollToBottom()` Scrolls to the bottom of the current `webContents`. #### `contents.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. Example: ```js const win = new BrowserWindow() // Adjusts the beginning of the selection 1 letter forward, // and the end of the selection 5 letters forward. win.webContents.adjustSelection({ start: 1, end: 5 }) // Adjusts the beginning of the selection 2 letters forward, // and the end of the selection 3 letters backward. win.webContents.adjustSelection({ start: 2, end: -3 }) ``` For a call of `win.webContents.adjustSelection({ start: 1, end: 5 })` Before: <img width="487" alt="Image Before Text Selection Adjustment" src="https://user-images.githubusercontent.com/2036040/231761306-cd4e7b15-c2ed-46cf-8e80-10811f6de83e.png"> After: <img width="487" alt="Image After Text Selection Adjustment" src="https://user-images.githubusercontent.com/2036040/231761169-887eb8ef-06fb-46e4-9efa-898bcb0d6a2b.png"> #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`](#contentsfindinpagetext-options) request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js title='main.js' const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | \[number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether _offscreen rendering_ is enabled. #### `contents.startPainting()` If _offscreen rendering_ is enabled and not painting, start painting. #### `contents.stopPainting()` If _offscreen rendering_ is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If _offscreen rendering_ is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If _offscreen rendering_ is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If _offscreen rendering_ is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If _offscreen rendering_ is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if _offscreen rendering_ is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been deprecated and will be removed in an upcoming version of macOS. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - an array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
docs/api/structures/browser-window-options.md
# BrowserWindowConstructorOptions Object * `width` Integer (optional) - Window's width in pixels. Default is `800`. * `height` Integer (optional) - Window's height in pixels. Default is `600`. * `x` Integer (optional) - (**required** if y is used) Window's left offset from screen. Default is to center the window. * `y` Integer (optional) - (**required** if x is used) Window's top offset from screen. Default is to center the window. * `useContentSize` boolean (optional) - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. * `center` boolean (optional) - Show window in the center of the screen. Default is `false`. * `minWidth` Integer (optional) - Window's minimum width. Default is `0`. * `minHeight` Integer (optional) - Window's minimum height. Default is `0`. * `maxWidth` Integer (optional) - Window's maximum width. Default is no limit. * `maxHeight` Integer (optional) - Window's maximum height. Default is no limit. * `resizable` boolean (optional) - Whether window is resizable. Default is `true`. * `movable` boolean (optional) _macOS_ _Windows_ - Whether window is movable. This is not implemented on Linux. Default is `true`. * `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is minimizable. This is not implemented on Linux. Default is `true`. * `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is maximizable. This is not implemented on Linux. Default is `true`. * `closable` boolean (optional) _macOS_ _Windows_ - Whether window is closable. This is not implemented on Linux. Default is `true`. * `focusable` boolean (optional) - Whether the window can be focused. Default is `true`. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. * `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of other windows. Default is `false`. * `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. * `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. * `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on macOS. Default is `false`. * `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar. Default is `false`. * `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control. * `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`. * `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. * `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is recommended to use `ICO` icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. * `show` boolean (optional) - Whether window should be shown when created. Default is `true`. * `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`. * `frame` boolean (optional) - Specify `false` to create a [frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`. * `parent` BrowserWindow (optional) - Specify parent window. Default is `null`. * `modal` boolean (optional) - Whether this is a modal window. This only works when the window is a child window. Default is `false`. * `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an inactive window will also click through to the web contents. Default is `false` on macOS. This option is not configurable on other platforms. * `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing. Default is `false`. * `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. * `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to be resized larger than screen. Only relevant for macOS, as other OSes allow larger-than-screen windows by default. Default is `false`. * `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information. * `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`. * `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS. * `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is `false`. * `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows). Default is `false`. On Windows, does not work unless the window is frameless. * `type` string (optional) - The type of window, default is normal window. See more about this below. * `visualEffectState` string (optional) _macOS_ - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are: * `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default. * `active` - The backdrop should always appear active. * `inactive` - The backdrop should always appear inactive. * `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar. Default is `default`. Possible values are: * `default` - Results in the standard title bar for macOS or Windows respectively. * `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown. * `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. * `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden title bar and a full size content window, the traffic light buttons will display when being hovered over in the top left of the window. **Note:** This option is currently experimental. * `trafficLightPosition` [Point](point.md) (optional) _macOS_ - Set a custom position for the traffic light buttons in frameless windows. * `roundedCorners` boolean (optional) _macOS_ - Whether frameless window should have rounded corners on macOS. Default is `true`. Setting this property to `false` will prevent the window from being fullscreenable. * `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows the title in the title bar in full screen mode on macOS for `hiddenInset` titleBarStyle. Default is `false`. * `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard window frame. Setting it to `false` will remove window shadow and window animations. Default is `true`. * `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to the window, only on macOS. Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are deprecated and have been removed in macOS Catalina (10.15). * `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window will grow to the preferred width of the web page when zoomed, `false` will cause it to zoom to the width of the screen. This will also affect the behavior when calling `maximize()` directly. Default is `false`. * `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows opening the window as a native tab. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows your `app` and window to receive the `new-window-for-tab` event. * `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features. * `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`. * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color. * `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height. When setting minimum or maximum window size with `minWidth`/`maxWidth`/ `minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from passing a size that does not follow size constraints to `setBounds`/`setSize` or to the constructor of `BrowserWindow`. The possible values and behaviors of the `type` option are platform dependent. Possible values are: * On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`, `notification`. * On macOS, possible types are `desktop`, `textured`, `panel`. * The `textured` type adds metal gradient appearance (`NSWindowStyleMaskTexturedBackground`). * The `desktop` type places the window at the desktop background window level (`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive focus, keyboard or mouse events, but you can use `globalShortcut` to receive input sparingly. * The `panel` type enables the window to float on top of full-screened apps by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally reserved for NSPanel, at runtime. Also, the window will appear on all spaces (desktops). * On Windows, possible type is `toolbar`. [overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables [overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_base_window.h" #include <string> #include <utility> #include <vector> #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); #if BUILDFLAG(ENABLE_OSR) // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } #endif // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); #else args->ThrowError("enable_desktop_capturer=true to use this feature"); #endif } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { menu_.Reset(isolate, menu.ToV8()); // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end()) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->second.Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), (*first_view).second); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& views_iter : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item.second), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.second.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #include <map> #include <memory> #include <string> #include <vector> #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "gin/handle.h" #include "shell/browser/native_window.h" #include "shell/browser/native_window_observer.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/trackable_object.h" namespace electron::api { class View; class BrowserView; class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, public NativeWindowObserver { public: static gin_helper::WrappableBase* New(gin_helper::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype); base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } NativeWindow* window() const { return window_.get(); } protected: // Common constructor. BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Creating independent BaseWindow instance. BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options); ~BaseWindow() override; // TrackableObject: void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; void OnWindowClosed() override; void OnWindowEndSession() override; void OnWindowBlur() override; void OnWindowFocus() override; void OnWindowShow() override; void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; void OnWindowRestore() override; void OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) override; void OnWindowResize() override; void OnWindowResized() override; void OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; void OnWindowSheetEnd() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; void OnWindowLeaveHtmlFullScreen() override; void OnWindowAlwaysOnTopChanged() override; void OnExecuteAppCommand(const std::string& command_name) override; void OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) override; void OnNewWindowForTab() override; void OnSystemContextMenu(int x, int y, bool* prevent_default) override; #if BUILDFLAG(IS_WIN) void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override; #endif // Public APIs of NativeWindow. void SetContentView(gin::Handle<View> view); void Close(); virtual void CloseImmediately(); virtual void Focus(); virtual void Blur(); bool IsFocused(); void Show(); void ShowInactive(); void Hide(); bool IsVisible(); bool IsEnabled(); void SetEnabled(bool enable); void Maximize(); void Unmaximize(); bool IsMaximized(); void Minimize(); void Restore(); bool IsMinimized(); void SetFullScreen(bool fullscreen); bool IsFullscreen(); void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetBounds(); void SetSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetSize(); void SetContentSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetContentSize(); void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetContentBounds(); bool IsNormal(); gfx::Rect GetNormalBounds(); void SetMinimumSize(int width, int height); std::vector<int> GetMinimumSize(); void SetMaximumSize(int width, int height); std::vector<int> GetMaximumSize(); void SetSheetOffset(double offsetY, gin_helper::Arguments* args); void SetResizable(bool resizable); bool IsResizable(); void SetMovable(bool movable); void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args); void MoveTop(); bool IsMovable(); void SetMinimizable(bool minimizable); bool IsMinimizable(); void SetMaximizable(bool maximizable); bool IsMaximizable(); void SetFullScreenable(bool fullscreenable); bool IsFullScreenable(); void SetClosable(bool closable); bool IsClosable(); void SetAlwaysOnTop(bool top, gin_helper::Arguments* args); bool IsAlwaysOnTop(); void Center(); void SetPosition(int x, int y, gin_helper::Arguments* args); std::vector<int> GetPosition(); void SetTitle(const std::string& title); std::string GetTitle(); void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); void FlashFrame(bool flash); void SetSkipTaskbar(bool skip); void SetExcludedFromShownWindowsMenu(bool excluded); bool IsExcludedFromShownWindowsMenu(); void SetSimpleFullScreen(bool simple_fullscreen); bool IsSimpleFullScreen(); void SetKiosk(bool kiosk); bool IsKiosk(); bool IsTabletMode() const; virtual void SetBackgroundColor(const std::string& color_name); std::string GetBackgroundColor(gin_helper::Arguments* args); void InvalidateShadow(); void SetHasShadow(bool has_shadow); bool HasShadow(); void SetOpacity(const double opacity); double GetOpacity(); void SetShape(const std::vector<gfx::Rect>& rects); void SetRepresentedFilename(const std::string& filename); std::string GetRepresentedFilename(); void SetDocumentEdited(bool edited); bool IsDocumentEdited(); void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args); void SetContentProtection(bool enable); void SetFocusable(bool focusable); bool IsFocusable(); void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu); void RemoveMenu(); void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args); virtual void SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view); virtual void AddBrowserView(gin::Handle<BrowserView> browser_view); virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view); virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args); virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const; virtual void ResetBrowserViews(); std::string GetMediaSourceId() const; v8::Local<v8::Value> GetNativeWindowHandle(); void SetProgressBar(double progress, gin_helper::Arguments* args); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args); bool IsVisibleOnAllWorkspaces(); void SetAutoHideCursor(bool auto_hide); virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value); #if BUILDFLAG(IS_MAC) std::string GetAlwaysOnTopLevel(); void SetWindowButtonVisibility(bool visible); bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(absl::optional<gfx::Point> position); absl::optional<gfx::Point> GetWindowButtonPosition() const; #endif #if BUILDFLAG(IS_MAC) bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); void RefreshTouchBarItem(const std::string& item_id); void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); void SelectPreviousTab(); void SelectNextTab(); void MergeAllWindows(); void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide(); void SetMenuBarVisibility(bool visible); bool IsMenuBarVisible(); void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args); void PreviewFile(const std::string& path, gin_helper::Arguments* args); void CloseFilePreview(); void SetGTKDarkThemeEnabled(bool use_dark_theme); // Public getters of NativeWindow. v8::Local<v8::Value> GetContentView() const; v8::Local<v8::Value> GetParentWindow() const; std::vector<v8::Local<v8::Object>> GetChildWindows() const; v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const; bool IsModal() const; // Extra APIs added in JS. bool SetThumbarButtons(gin_helper::Arguments* args); #if defined(TOOLKIT_VIEWS) void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon); void SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error); #endif #if BUILDFLAG(IS_WIN) typedef base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)> MessageCallback; bool HookWindowMessage(UINT message, const MessageCallback& callback); bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); bool SetThumbnailClip(const gfx::Rect& region); bool SetThumbnailToolTip(const std::string& tooltip); void SetAppDetails(const gin_helper::Dictionary& options); #endif int32_t GetID() const; // Helpers. // Remove BrowserView. void ResetBrowserView(); // Remove this window from parent window's |child_windows_|. void RemoveFromParentChildWindows(); template <typename... Args> void EmitEventSoon(base::StringPiece eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), weak_factory_.GetWeakPtr(), eventName)); } #if BUILDFLAG(IS_WIN) typedef std::map<UINT, MessageCallback> MessageCallbackMap; MessageCallbackMap messages_callback_map_; #endif v8::Global<v8::Value> content_view_; std::map<int32_t, v8::Global<v8::Value>> browser_views_; v8::Global<v8::Value> menu_; v8::Global<v8::Value> parent_window_; KeyWeakMap<int> child_windows_; std::unique_ptr<NativeWindow> window_; // Reference to JS wrapper to prevent garbage collection. v8::Global<v8::Value> self_ref_; base::WeakPtrFactory<BaseWindow> weak_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (std::find(draggable_region_providers_.begin(), draggable_region_providers_.end(), provider) == draggable_region_providers_.end()) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace views { class UnhandledKeyboardEventHandler; } namespace electron { class GlobalMenuBarX11; class RootView; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); std::unique_ptr<RootView> root_view_; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/options_switches.h" namespace electron { namespace options { const char kTitle[] = "title"; const char kIcon[] = "icon"; const char kFrame[] = "frame"; const char kShow[] = "show"; const char kCenter[] = "center"; const char kX[] = "x"; const char kY[] = "y"; const char kWidth[] = "width"; const char kHeight[] = "height"; const char kMinWidth[] = "minWidth"; const char kMinHeight[] = "minHeight"; const char kMaxWidth[] = "maxWidth"; const char kMaxHeight[] = "maxHeight"; const char kResizable[] = "resizable"; const char kMovable[] = "movable"; const char kMinimizable[] = "minimizable"; const char kMaximizable[] = "maximizable"; const char kFullScreenable[] = "fullscreenable"; const char kClosable[] = "closable"; const char kFullscreen[] = "fullscreen"; const char kTrafficLightPosition[] = "trafficLightPosition"; const char kRoundedCorners[] = "roundedCorners"; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. const char kOverlayButtonColor[] = "color"; const char kOverlaySymbolColor[] = "symbolColor"; // The custom height for Window Controls Overlay. const char kOverlayHeight[] = "height"; // whether to keep the window out of mission control const char kHiddenInMissionControl[] = "hiddenInMissionControl"; // Whether the window should show in taskbar. const char kSkipTaskbar[] = "skipTaskbar"; // Start with the kiosk mode, see Opera's page for description: // http://www.opera.com/support/mastering/kiosk/ const char kKiosk[] = "kiosk"; const char kSimpleFullScreen[] = "simpleFullscreen"; // Make windows stays on the top of all other windows. const char kAlwaysOnTop[] = "alwaysOnTop"; // Enable the NSView to accept first mouse event. const char kAcceptFirstMouse[] = "acceptFirstMouse"; // Whether window size should include window frame. const char kUseContentSize[] = "useContentSize"; // Whether window zoom should be to page width. const char kZoomToPageWidth[] = "zoomToPageWidth"; // Whether always show title text in full screen is enabled. const char kFullscreenWindowTitle[] = "fullscreenWindowTitle"; // The requested title bar style for the window const char kTitleBarStyle[] = "titleBarStyle"; // Tabbing identifier for the window if native tabs are enabled on macOS. const char kTabbingIdentifier[] = "tabbingIdentifier"; // The menu bar is hidden unless "Alt" is pressed. const char kAutoHideMenuBar[] = "autoHideMenuBar"; // Enable window to be resized larger than screen. const char kEnableLargerThanScreen[] = "enableLargerThanScreen"; // Forces to use dark theme on Linux. const char kDarkTheme[] = "darkTheme"; // Whether the window should be transparent. const char kTransparent[] = "transparent"; // Window type hint. const char kType[] = "type"; // Disable auto-hiding cursor. const char kDisableAutoHideCursor[] = "disableAutoHideCursor"; // Use the macOS' standard window instead of the textured window. const char kStandardWindow[] = "standardWindow"; // Default browser window background color. const char kBackgroundColor[] = "backgroundColor"; // Whether the window should have a shadow. const char kHasShadow[] = "hasShadow"; // Browser window opacity const char kOpacity[] = "opacity"; // Whether the window can be activated. const char kFocusable[] = "focusable"; // The WebPreferences. const char kWebPreferences[] = "webPreferences"; // Add a vibrancy effect to the browser window const char kVibrancyType[] = "vibrancy"; // Specify how the material appearance should reflect window activity state on // macOS. const char kVisualEffectState[] = "visualEffectState"; // The factor of which page should be zoomed. const char kZoomFactor[] = "zoomFactor"; // Script that will be loaded by guest WebContents before other scripts. const char kPreloadScript[] = "preload"; const char kPreloadScripts[] = "preloadScripts"; // Enable the node integration. const char kNodeIntegration[] = "nodeIntegration"; // Enable context isolation of Electron APIs and preload script const char kContextIsolation[] = "contextIsolation"; // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; // Enable the rubber banding effect. const char kScrollBounce[] = "scrollBounce"; // Enable blink features. const char kEnableBlinkFeatures[] = "enableBlinkFeatures"; // Disable blink features. const char kDisableBlinkFeatures[] = "disableBlinkFeatures"; // Enable the node integration in WebWorker. const char kNodeIntegrationInWorker[] = "nodeIntegrationInWorker"; // Enable the web view tag. const char kWebviewTag[] = "webviewTag"; const char kCustomArgs[] = "additionalArguments"; const char kPlugins[] = "plugins"; const char kSandbox[] = "sandbox"; const char kWebSecurity[] = "webSecurity"; const char kAllowRunningInsecureContent[] = "allowRunningInsecureContent"; const char kOffscreen[] = "offscreen"; const char kNodeIntegrationInSubFrames[] = "nodeIntegrationInSubFrames"; // Disable window resizing when HTML Fullscreen API is activated. const char kDisableHtmlFullscreenWindowResize[] = "disableHtmlFullscreenWindowResize"; // Enables JavaScript support. const char kJavaScript[] = "javascript"; // Enables image support. const char kImages[] = "images"; // Image animation policy. const char kImageAnimationPolicy[] = "imageAnimationPolicy"; // Make TextArea elements resizable. const char kTextAreasAreResizable[] = "textAreasAreResizable"; // Enables WebGL support. const char kWebGL[] = "webgl"; // Whether dragging and dropping a file or link onto the page causes a // navigation. const char kNavigateOnDragDrop[] = "navigateOnDragDrop"; const char kHiddenPage[] = "hiddenPage"; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) const char kSpellcheck[] = "spellcheck"; #endif const char kEnableWebSQL[] = "enableWebSQL"; const char kEnablePreferredSizeMode[] = "enablePreferredSizeMode"; const char ktitleBarOverlay[] = "titleBarOverlay"; } // namespace options namespace switches { // Enable chromium sandbox. const char kEnableSandbox[] = "enable-sandbox"; // Ppapi Flash path. const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; // Disable HTTP cache. const char kDisableHttpCache[] = "disable-http-cache"; // The list of standard schemes. const char kStandardSchemes[] = "standard-schemes"; // Register schemes to handle service worker. const char kServiceWorkerSchemes[] = "service-worker-schemes"; // Register schemes as secure. const char kSecureSchemes[] = "secure-schemes"; // Register schemes as bypassing CSP. const char kBypassCSPSchemes[] = "bypasscsp-schemes"; // Register schemes as support fetch API. const char kFetchSchemes[] = "fetch-schemes"; // Register schemes as CORS enabled. const char kCORSSchemes[] = "cors-schemes"; // Register schemes as streaming responses. const char kStreamingSchemes[] = "streaming-schemes"; // The browser process app model ID const char kAppUserModelId[] = "app-user-model-id"; // The application path const char kAppPath[] = "app-path"; // The command line switch versions of the options. const char kScrollBounce[] = "scroll-bounce"; // Command switch passed to renderer process to control nodeIntegration. const char kNodeIntegrationInWorker[] = "node-integration-in-worker"; // Widevine options // Path to Widevine CDM binaries. const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; // Forces the maximum disk space to be used by the disk cache, in bytes. const char kDiskCacheSize[] = "disk-cache-size"; // Ignore the limit of 6 connections per host. const char kIgnoreConnectionsLimit[] = "ignore-connections-limit"; // Whitelist containing servers for which Integrated Authentication is enabled. const char kAuthServerWhitelist[] = "auth-server-whitelist"; // Whitelist containing servers for which Kerberos delegation is allowed. const char kAuthNegotiateDelegateWhitelist[] = "auth-negotiate-delegate-whitelist"; // If set, include the port in generated Kerberos SPNs. const char kEnableAuthNegotiatePort[] = "enable-auth-negotiate-port"; // If set, NTLM v2 is disabled for POSIX platforms. const char kDisableNTLMv2[] = "disable-ntlm-v2"; const char kEnableWebSQL[] = "enable-websql"; } // namespace switches } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #define ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #include "electron/buildflags/buildflags.h" namespace electron { namespace options { extern const char kTitle[]; extern const char kIcon[]; extern const char kFrame[]; extern const char kShow[]; extern const char kCenter[]; extern const char kX[]; extern const char kY[]; extern const char kWidth[]; extern const char kHeight[]; extern const char kMinWidth[]; extern const char kMinHeight[]; extern const char kMaxWidth[]; extern const char kMaxHeight[]; extern const char kResizable[]; extern const char kMovable[]; extern const char kMinimizable[]; extern const char kMaximizable[]; extern const char kFullScreenable[]; extern const char kClosable[]; extern const char kHiddenInMissionControl[]; extern const char kFullscreen[]; extern const char kSkipTaskbar[]; extern const char kKiosk[]; extern const char kSimpleFullScreen[]; extern const char kAlwaysOnTop[]; extern const char kAcceptFirstMouse[]; extern const char kUseContentSize[]; extern const char kZoomToPageWidth[]; extern const char kFullscreenWindowTitle[]; extern const char kTitleBarStyle[]; extern const char kTabbingIdentifier[]; extern const char kAutoHideMenuBar[]; extern const char kEnableLargerThanScreen[]; extern const char kDarkTheme[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; extern const char kStandardWindow[]; extern const char kBackgroundColor[]; extern const char kHasShadow[]; extern const char kOpacity[]; extern const char kFocusable[]; extern const char kWebPreferences[]; extern const char kVibrancyType[]; extern const char kVisualEffectState[]; extern const char kTrafficLightPosition[]; extern const char kRoundedCorners[]; extern const char ktitleBarOverlay[]; extern const char kOverlayButtonColor[]; extern const char kOverlaySymbolColor[]; extern const char kOverlayHeight[]; // WebPreferences. extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadScripts[]; extern const char kNodeIntegration[]; extern const char kContextIsolation[]; extern const char kExperimentalFeatures[]; extern const char kScrollBounce[]; extern const char kEnableBlinkFeatures[]; extern const char kDisableBlinkFeatures[]; extern const char kNodeIntegrationInWorker[]; extern const char kWebviewTag[]; extern const char kCustomArgs[]; extern const char kPlugins[]; extern const char kSandbox[]; extern const char kWebSecurity[]; extern const char kAllowRunningInsecureContent[]; extern const char kOffscreen[]; extern const char kNodeIntegrationInSubFrames[]; extern const char kDisableHtmlFullscreenWindowResize[]; extern const char kJavaScript[]; extern const char kImages[]; extern const char kImageAnimationPolicy[]; extern const char kTextAreasAreResizable[]; extern const char kWebGL[]; extern const char kNavigateOnDragDrop[]; extern const char kEnableWebSQL[]; extern const char kEnablePreferredSizeMode[]; extern const char kHiddenPage[]; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) extern const char kSpellcheck[]; #endif } // namespace options // Following are actually command line switches, should be moved to other files. namespace switches { extern const char kEnableSandbox[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; extern const char kDisableHttpCache[]; extern const char kStandardSchemes[]; extern const char kServiceWorkerSchemes[]; extern const char kSecureSchemes[]; extern const char kBypassCSPSchemes[]; extern const char kFetchSchemes[]; extern const char kCORSSchemes[]; extern const char kStreamingSchemes[]; extern const char kAppUserModelId[]; extern const char kAppPath[]; extern const char kScrollBounce[]; extern const char kNodeIntegrationInWorker[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; extern const char kDiskCacheSize[]; extern const char kIgnoreConnectionsLimit[]; extern const char kAuthServerWhitelist[]; extern const char kAuthNegotiateDelegateWhitelist[]; extern const char kEnableAuthNegotiatePort[]; extern const char kDisableNTLMv2[]; extern const char kEnableWebSQL[]; } // namespace switches } // namespace electron #endif // ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been deprecated and will be removed in an upcoming version of macOS. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - an array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
docs/api/structures/browser-window-options.md
# BrowserWindowConstructorOptions Object * `width` Integer (optional) - Window's width in pixels. Default is `800`. * `height` Integer (optional) - Window's height in pixels. Default is `600`. * `x` Integer (optional) - (**required** if y is used) Window's left offset from screen. Default is to center the window. * `y` Integer (optional) - (**required** if x is used) Window's top offset from screen. Default is to center the window. * `useContentSize` boolean (optional) - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. * `center` boolean (optional) - Show window in the center of the screen. Default is `false`. * `minWidth` Integer (optional) - Window's minimum width. Default is `0`. * `minHeight` Integer (optional) - Window's minimum height. Default is `0`. * `maxWidth` Integer (optional) - Window's maximum width. Default is no limit. * `maxHeight` Integer (optional) - Window's maximum height. Default is no limit. * `resizable` boolean (optional) - Whether window is resizable. Default is `true`. * `movable` boolean (optional) _macOS_ _Windows_ - Whether window is movable. This is not implemented on Linux. Default is `true`. * `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is minimizable. This is not implemented on Linux. Default is `true`. * `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is maximizable. This is not implemented on Linux. Default is `true`. * `closable` boolean (optional) _macOS_ _Windows_ - Whether window is closable. This is not implemented on Linux. Default is `true`. * `focusable` boolean (optional) - Whether the window can be focused. Default is `true`. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. * `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of other windows. Default is `false`. * `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. * `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. * `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on macOS. Default is `false`. * `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar. Default is `false`. * `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control. * `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`. * `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. * `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is recommended to use `ICO` icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. * `show` boolean (optional) - Whether window should be shown when created. Default is `true`. * `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`. * `frame` boolean (optional) - Specify `false` to create a [frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`. * `parent` BrowserWindow (optional) - Specify parent window. Default is `null`. * `modal` boolean (optional) - Whether this is a modal window. This only works when the window is a child window. Default is `false`. * `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an inactive window will also click through to the web contents. Default is `false` on macOS. This option is not configurable on other platforms. * `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing. Default is `false`. * `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. * `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to be resized larger than screen. Only relevant for macOS, as other OSes allow larger-than-screen windows by default. Default is `false`. * `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information. * `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`. * `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS. * `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is `false`. * `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows). Default is `false`. On Windows, does not work unless the window is frameless. * `type` string (optional) - The type of window, default is normal window. See more about this below. * `visualEffectState` string (optional) _macOS_ - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are: * `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default. * `active` - The backdrop should always appear active. * `inactive` - The backdrop should always appear inactive. * `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar. Default is `default`. Possible values are: * `default` - Results in the standard title bar for macOS or Windows respectively. * `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown. * `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. * `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden title bar and a full size content window, the traffic light buttons will display when being hovered over in the top left of the window. **Note:** This option is currently experimental. * `trafficLightPosition` [Point](point.md) (optional) _macOS_ - Set a custom position for the traffic light buttons in frameless windows. * `roundedCorners` boolean (optional) _macOS_ - Whether frameless window should have rounded corners on macOS. Default is `true`. Setting this property to `false` will prevent the window from being fullscreenable. * `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows the title in the title bar in full screen mode on macOS for `hiddenInset` titleBarStyle. Default is `false`. * `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard window frame. Setting it to `false` will remove window shadow and window animations. Default is `true`. * `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to the window, only on macOS. Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are deprecated and have been removed in macOS Catalina (10.15). * `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window will grow to the preferred width of the web page when zoomed, `false` will cause it to zoom to the width of the screen. This will also affect the behavior when calling `maximize()` directly. Default is `false`. * `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows opening the window as a native tab. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows your `app` and window to receive the `new-window-for-tab` event. * `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features. * `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`. * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color. * `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height. When setting minimum or maximum window size with `minWidth`/`maxWidth`/ `minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from passing a size that does not follow size constraints to `setBounds`/`setSize` or to the constructor of `BrowserWindow`. The possible values and behaviors of the `type` option are platform dependent. Possible values are: * On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`, `notification`. * On macOS, possible types are `desktop`, `textured`, `panel`. * The `textured` type adds metal gradient appearance (`NSWindowStyleMaskTexturedBackground`). * The `desktop` type places the window at the desktop background window level (`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive focus, keyboard or mouse events, but you can use `globalShortcut` to receive input sparingly. * The `panel` type enables the window to float on top of full-screened apps by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally reserved for NSPanel, at runtime. Also, the window will appear on all spaces (desktops). * On Windows, possible type is `toolbar`. [overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables [overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_base_window.h" #include <string> #include <utility> #include <vector> #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); #if BUILDFLAG(ENABLE_OSR) // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } #endif // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); #else args->ThrowError("enable_desktop_capturer=true to use this feature"); #endif } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { menu_.Reset(isolate, menu.ToV8()); // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end()) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->second.Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), (*first_view).second); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& views_iter : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item.second), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.second.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #include <map> #include <memory> #include <string> #include <vector> #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "gin/handle.h" #include "shell/browser/native_window.h" #include "shell/browser/native_window_observer.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/trackable_object.h" namespace electron::api { class View; class BrowserView; class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, public NativeWindowObserver { public: static gin_helper::WrappableBase* New(gin_helper::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype); base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } NativeWindow* window() const { return window_.get(); } protected: // Common constructor. BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Creating independent BaseWindow instance. BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options); ~BaseWindow() override; // TrackableObject: void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; void OnWindowClosed() override; void OnWindowEndSession() override; void OnWindowBlur() override; void OnWindowFocus() override; void OnWindowShow() override; void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; void OnWindowRestore() override; void OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) override; void OnWindowResize() override; void OnWindowResized() override; void OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; void OnWindowSheetEnd() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; void OnWindowLeaveHtmlFullScreen() override; void OnWindowAlwaysOnTopChanged() override; void OnExecuteAppCommand(const std::string& command_name) override; void OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) override; void OnNewWindowForTab() override; void OnSystemContextMenu(int x, int y, bool* prevent_default) override; #if BUILDFLAG(IS_WIN) void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override; #endif // Public APIs of NativeWindow. void SetContentView(gin::Handle<View> view); void Close(); virtual void CloseImmediately(); virtual void Focus(); virtual void Blur(); bool IsFocused(); void Show(); void ShowInactive(); void Hide(); bool IsVisible(); bool IsEnabled(); void SetEnabled(bool enable); void Maximize(); void Unmaximize(); bool IsMaximized(); void Minimize(); void Restore(); bool IsMinimized(); void SetFullScreen(bool fullscreen); bool IsFullscreen(); void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetBounds(); void SetSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetSize(); void SetContentSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetContentSize(); void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetContentBounds(); bool IsNormal(); gfx::Rect GetNormalBounds(); void SetMinimumSize(int width, int height); std::vector<int> GetMinimumSize(); void SetMaximumSize(int width, int height); std::vector<int> GetMaximumSize(); void SetSheetOffset(double offsetY, gin_helper::Arguments* args); void SetResizable(bool resizable); bool IsResizable(); void SetMovable(bool movable); void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args); void MoveTop(); bool IsMovable(); void SetMinimizable(bool minimizable); bool IsMinimizable(); void SetMaximizable(bool maximizable); bool IsMaximizable(); void SetFullScreenable(bool fullscreenable); bool IsFullScreenable(); void SetClosable(bool closable); bool IsClosable(); void SetAlwaysOnTop(bool top, gin_helper::Arguments* args); bool IsAlwaysOnTop(); void Center(); void SetPosition(int x, int y, gin_helper::Arguments* args); std::vector<int> GetPosition(); void SetTitle(const std::string& title); std::string GetTitle(); void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); void FlashFrame(bool flash); void SetSkipTaskbar(bool skip); void SetExcludedFromShownWindowsMenu(bool excluded); bool IsExcludedFromShownWindowsMenu(); void SetSimpleFullScreen(bool simple_fullscreen); bool IsSimpleFullScreen(); void SetKiosk(bool kiosk); bool IsKiosk(); bool IsTabletMode() const; virtual void SetBackgroundColor(const std::string& color_name); std::string GetBackgroundColor(gin_helper::Arguments* args); void InvalidateShadow(); void SetHasShadow(bool has_shadow); bool HasShadow(); void SetOpacity(const double opacity); double GetOpacity(); void SetShape(const std::vector<gfx::Rect>& rects); void SetRepresentedFilename(const std::string& filename); std::string GetRepresentedFilename(); void SetDocumentEdited(bool edited); bool IsDocumentEdited(); void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args); void SetContentProtection(bool enable); void SetFocusable(bool focusable); bool IsFocusable(); void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu); void RemoveMenu(); void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args); virtual void SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view); virtual void AddBrowserView(gin::Handle<BrowserView> browser_view); virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view); virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args); virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const; virtual void ResetBrowserViews(); std::string GetMediaSourceId() const; v8::Local<v8::Value> GetNativeWindowHandle(); void SetProgressBar(double progress, gin_helper::Arguments* args); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args); bool IsVisibleOnAllWorkspaces(); void SetAutoHideCursor(bool auto_hide); virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value); #if BUILDFLAG(IS_MAC) std::string GetAlwaysOnTopLevel(); void SetWindowButtonVisibility(bool visible); bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(absl::optional<gfx::Point> position); absl::optional<gfx::Point> GetWindowButtonPosition() const; #endif #if BUILDFLAG(IS_MAC) bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); void RefreshTouchBarItem(const std::string& item_id); void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); void SelectPreviousTab(); void SelectNextTab(); void MergeAllWindows(); void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide(); void SetMenuBarVisibility(bool visible); bool IsMenuBarVisible(); void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args); void PreviewFile(const std::string& path, gin_helper::Arguments* args); void CloseFilePreview(); void SetGTKDarkThemeEnabled(bool use_dark_theme); // Public getters of NativeWindow. v8::Local<v8::Value> GetContentView() const; v8::Local<v8::Value> GetParentWindow() const; std::vector<v8::Local<v8::Object>> GetChildWindows() const; v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const; bool IsModal() const; // Extra APIs added in JS. bool SetThumbarButtons(gin_helper::Arguments* args); #if defined(TOOLKIT_VIEWS) void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon); void SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error); #endif #if BUILDFLAG(IS_WIN) typedef base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)> MessageCallback; bool HookWindowMessage(UINT message, const MessageCallback& callback); bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); bool SetThumbnailClip(const gfx::Rect& region); bool SetThumbnailToolTip(const std::string& tooltip); void SetAppDetails(const gin_helper::Dictionary& options); #endif int32_t GetID() const; // Helpers. // Remove BrowserView. void ResetBrowserView(); // Remove this window from parent window's |child_windows_|. void RemoveFromParentChildWindows(); template <typename... Args> void EmitEventSoon(base::StringPiece eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), weak_factory_.GetWeakPtr(), eventName)); } #if BUILDFLAG(IS_WIN) typedef std::map<UINT, MessageCallback> MessageCallbackMap; MessageCallbackMap messages_callback_map_; #endif v8::Global<v8::Value> content_view_; std::map<int32_t, v8::Global<v8::Value>> browser_views_; v8::Global<v8::Value> menu_; v8::Global<v8::Value> parent_window_; KeyWeakMap<int> child_windows_; std::unique_ptr<NativeWindow> window_; // Reference to JS wrapper to prevent garbage collection. v8::Global<v8::Value> self_ref_; base::WeakPtrFactory<BaseWindow> weak_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (std::find(draggable_region_providers_.begin(), draggable_region_providers_.end(), provider) == draggable_region_providers_.end()) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace views { class UnhandledKeyboardEventHandler; } namespace electron { class GlobalMenuBarX11; class RootView; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); std::unique_ptr<RootView> root_view_; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/options_switches.h" namespace electron { namespace options { const char kTitle[] = "title"; const char kIcon[] = "icon"; const char kFrame[] = "frame"; const char kShow[] = "show"; const char kCenter[] = "center"; const char kX[] = "x"; const char kY[] = "y"; const char kWidth[] = "width"; const char kHeight[] = "height"; const char kMinWidth[] = "minWidth"; const char kMinHeight[] = "minHeight"; const char kMaxWidth[] = "maxWidth"; const char kMaxHeight[] = "maxHeight"; const char kResizable[] = "resizable"; const char kMovable[] = "movable"; const char kMinimizable[] = "minimizable"; const char kMaximizable[] = "maximizable"; const char kFullScreenable[] = "fullscreenable"; const char kClosable[] = "closable"; const char kFullscreen[] = "fullscreen"; const char kTrafficLightPosition[] = "trafficLightPosition"; const char kRoundedCorners[] = "roundedCorners"; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. const char kOverlayButtonColor[] = "color"; const char kOverlaySymbolColor[] = "symbolColor"; // The custom height for Window Controls Overlay. const char kOverlayHeight[] = "height"; // whether to keep the window out of mission control const char kHiddenInMissionControl[] = "hiddenInMissionControl"; // Whether the window should show in taskbar. const char kSkipTaskbar[] = "skipTaskbar"; // Start with the kiosk mode, see Opera's page for description: // http://www.opera.com/support/mastering/kiosk/ const char kKiosk[] = "kiosk"; const char kSimpleFullScreen[] = "simpleFullscreen"; // Make windows stays on the top of all other windows. const char kAlwaysOnTop[] = "alwaysOnTop"; // Enable the NSView to accept first mouse event. const char kAcceptFirstMouse[] = "acceptFirstMouse"; // Whether window size should include window frame. const char kUseContentSize[] = "useContentSize"; // Whether window zoom should be to page width. const char kZoomToPageWidth[] = "zoomToPageWidth"; // Whether always show title text in full screen is enabled. const char kFullscreenWindowTitle[] = "fullscreenWindowTitle"; // The requested title bar style for the window const char kTitleBarStyle[] = "titleBarStyle"; // Tabbing identifier for the window if native tabs are enabled on macOS. const char kTabbingIdentifier[] = "tabbingIdentifier"; // The menu bar is hidden unless "Alt" is pressed. const char kAutoHideMenuBar[] = "autoHideMenuBar"; // Enable window to be resized larger than screen. const char kEnableLargerThanScreen[] = "enableLargerThanScreen"; // Forces to use dark theme on Linux. const char kDarkTheme[] = "darkTheme"; // Whether the window should be transparent. const char kTransparent[] = "transparent"; // Window type hint. const char kType[] = "type"; // Disable auto-hiding cursor. const char kDisableAutoHideCursor[] = "disableAutoHideCursor"; // Use the macOS' standard window instead of the textured window. const char kStandardWindow[] = "standardWindow"; // Default browser window background color. const char kBackgroundColor[] = "backgroundColor"; // Whether the window should have a shadow. const char kHasShadow[] = "hasShadow"; // Browser window opacity const char kOpacity[] = "opacity"; // Whether the window can be activated. const char kFocusable[] = "focusable"; // The WebPreferences. const char kWebPreferences[] = "webPreferences"; // Add a vibrancy effect to the browser window const char kVibrancyType[] = "vibrancy"; // Specify how the material appearance should reflect window activity state on // macOS. const char kVisualEffectState[] = "visualEffectState"; // The factor of which page should be zoomed. const char kZoomFactor[] = "zoomFactor"; // Script that will be loaded by guest WebContents before other scripts. const char kPreloadScript[] = "preload"; const char kPreloadScripts[] = "preloadScripts"; // Enable the node integration. const char kNodeIntegration[] = "nodeIntegration"; // Enable context isolation of Electron APIs and preload script const char kContextIsolation[] = "contextIsolation"; // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; // Enable the rubber banding effect. const char kScrollBounce[] = "scrollBounce"; // Enable blink features. const char kEnableBlinkFeatures[] = "enableBlinkFeatures"; // Disable blink features. const char kDisableBlinkFeatures[] = "disableBlinkFeatures"; // Enable the node integration in WebWorker. const char kNodeIntegrationInWorker[] = "nodeIntegrationInWorker"; // Enable the web view tag. const char kWebviewTag[] = "webviewTag"; const char kCustomArgs[] = "additionalArguments"; const char kPlugins[] = "plugins"; const char kSandbox[] = "sandbox"; const char kWebSecurity[] = "webSecurity"; const char kAllowRunningInsecureContent[] = "allowRunningInsecureContent"; const char kOffscreen[] = "offscreen"; const char kNodeIntegrationInSubFrames[] = "nodeIntegrationInSubFrames"; // Disable window resizing when HTML Fullscreen API is activated. const char kDisableHtmlFullscreenWindowResize[] = "disableHtmlFullscreenWindowResize"; // Enables JavaScript support. const char kJavaScript[] = "javascript"; // Enables image support. const char kImages[] = "images"; // Image animation policy. const char kImageAnimationPolicy[] = "imageAnimationPolicy"; // Make TextArea elements resizable. const char kTextAreasAreResizable[] = "textAreasAreResizable"; // Enables WebGL support. const char kWebGL[] = "webgl"; // Whether dragging and dropping a file or link onto the page causes a // navigation. const char kNavigateOnDragDrop[] = "navigateOnDragDrop"; const char kHiddenPage[] = "hiddenPage"; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) const char kSpellcheck[] = "spellcheck"; #endif const char kEnableWebSQL[] = "enableWebSQL"; const char kEnablePreferredSizeMode[] = "enablePreferredSizeMode"; const char ktitleBarOverlay[] = "titleBarOverlay"; } // namespace options namespace switches { // Enable chromium sandbox. const char kEnableSandbox[] = "enable-sandbox"; // Ppapi Flash path. const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; // Disable HTTP cache. const char kDisableHttpCache[] = "disable-http-cache"; // The list of standard schemes. const char kStandardSchemes[] = "standard-schemes"; // Register schemes to handle service worker. const char kServiceWorkerSchemes[] = "service-worker-schemes"; // Register schemes as secure. const char kSecureSchemes[] = "secure-schemes"; // Register schemes as bypassing CSP. const char kBypassCSPSchemes[] = "bypasscsp-schemes"; // Register schemes as support fetch API. const char kFetchSchemes[] = "fetch-schemes"; // Register schemes as CORS enabled. const char kCORSSchemes[] = "cors-schemes"; // Register schemes as streaming responses. const char kStreamingSchemes[] = "streaming-schemes"; // The browser process app model ID const char kAppUserModelId[] = "app-user-model-id"; // The application path const char kAppPath[] = "app-path"; // The command line switch versions of the options. const char kScrollBounce[] = "scroll-bounce"; // Command switch passed to renderer process to control nodeIntegration. const char kNodeIntegrationInWorker[] = "node-integration-in-worker"; // Widevine options // Path to Widevine CDM binaries. const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; // Forces the maximum disk space to be used by the disk cache, in bytes. const char kDiskCacheSize[] = "disk-cache-size"; // Ignore the limit of 6 connections per host. const char kIgnoreConnectionsLimit[] = "ignore-connections-limit"; // Whitelist containing servers for which Integrated Authentication is enabled. const char kAuthServerWhitelist[] = "auth-server-whitelist"; // Whitelist containing servers for which Kerberos delegation is allowed. const char kAuthNegotiateDelegateWhitelist[] = "auth-negotiate-delegate-whitelist"; // If set, include the port in generated Kerberos SPNs. const char kEnableAuthNegotiatePort[] = "enable-auth-negotiate-port"; // If set, NTLM v2 is disabled for POSIX platforms. const char kDisableNTLMv2[] = "disable-ntlm-v2"; const char kEnableWebSQL[] = "enable-websql"; } // namespace switches } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #define ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #include "electron/buildflags/buildflags.h" namespace electron { namespace options { extern const char kTitle[]; extern const char kIcon[]; extern const char kFrame[]; extern const char kShow[]; extern const char kCenter[]; extern const char kX[]; extern const char kY[]; extern const char kWidth[]; extern const char kHeight[]; extern const char kMinWidth[]; extern const char kMinHeight[]; extern const char kMaxWidth[]; extern const char kMaxHeight[]; extern const char kResizable[]; extern const char kMovable[]; extern const char kMinimizable[]; extern const char kMaximizable[]; extern const char kFullScreenable[]; extern const char kClosable[]; extern const char kHiddenInMissionControl[]; extern const char kFullscreen[]; extern const char kSkipTaskbar[]; extern const char kKiosk[]; extern const char kSimpleFullScreen[]; extern const char kAlwaysOnTop[]; extern const char kAcceptFirstMouse[]; extern const char kUseContentSize[]; extern const char kZoomToPageWidth[]; extern const char kFullscreenWindowTitle[]; extern const char kTitleBarStyle[]; extern const char kTabbingIdentifier[]; extern const char kAutoHideMenuBar[]; extern const char kEnableLargerThanScreen[]; extern const char kDarkTheme[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; extern const char kStandardWindow[]; extern const char kBackgroundColor[]; extern const char kHasShadow[]; extern const char kOpacity[]; extern const char kFocusable[]; extern const char kWebPreferences[]; extern const char kVibrancyType[]; extern const char kVisualEffectState[]; extern const char kTrafficLightPosition[]; extern const char kRoundedCorners[]; extern const char ktitleBarOverlay[]; extern const char kOverlayButtonColor[]; extern const char kOverlaySymbolColor[]; extern const char kOverlayHeight[]; // WebPreferences. extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadScripts[]; extern const char kNodeIntegration[]; extern const char kContextIsolation[]; extern const char kExperimentalFeatures[]; extern const char kScrollBounce[]; extern const char kEnableBlinkFeatures[]; extern const char kDisableBlinkFeatures[]; extern const char kNodeIntegrationInWorker[]; extern const char kWebviewTag[]; extern const char kCustomArgs[]; extern const char kPlugins[]; extern const char kSandbox[]; extern const char kWebSecurity[]; extern const char kAllowRunningInsecureContent[]; extern const char kOffscreen[]; extern const char kNodeIntegrationInSubFrames[]; extern const char kDisableHtmlFullscreenWindowResize[]; extern const char kJavaScript[]; extern const char kImages[]; extern const char kImageAnimationPolicy[]; extern const char kTextAreasAreResizable[]; extern const char kWebGL[]; extern const char kNavigateOnDragDrop[]; extern const char kEnableWebSQL[]; extern const char kEnablePreferredSizeMode[]; extern const char kHiddenPage[]; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) extern const char kSpellcheck[]; #endif } // namespace options // Following are actually command line switches, should be moved to other files. namespace switches { extern const char kEnableSandbox[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; extern const char kDisableHttpCache[]; extern const char kStandardSchemes[]; extern const char kServiceWorkerSchemes[]; extern const char kSecureSchemes[]; extern const char kBypassCSPSchemes[]; extern const char kFetchSchemes[]; extern const char kCORSSchemes[]; extern const char kStreamingSchemes[]; extern const char kAppUserModelId[]; extern const char kAppPath[]; extern const char kScrollBounce[]; extern const char kNodeIntegrationInWorker[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; extern const char kDiskCacheSize[]; extern const char kIgnoreConnectionsLimit[]; extern const char kAuthServerWhitelist[]; extern const char kAuthNegotiateDelegateWhitelist[]; extern const char kEnableAuthNegotiatePort[]; extern const char kDisableNTLMv2[]; extern const char kEnableWebSQL[]; } // namespace switches } // namespace electron #endif // ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been deprecated and will be removed in an upcoming version of macOS. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - an array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
docs/api/structures/browser-window-options.md
# BrowserWindowConstructorOptions Object * `width` Integer (optional) - Window's width in pixels. Default is `800`. * `height` Integer (optional) - Window's height in pixels. Default is `600`. * `x` Integer (optional) - (**required** if y is used) Window's left offset from screen. Default is to center the window. * `y` Integer (optional) - (**required** if x is used) Window's top offset from screen. Default is to center the window. * `useContentSize` boolean (optional) - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. * `center` boolean (optional) - Show window in the center of the screen. Default is `false`. * `minWidth` Integer (optional) - Window's minimum width. Default is `0`. * `minHeight` Integer (optional) - Window's minimum height. Default is `0`. * `maxWidth` Integer (optional) - Window's maximum width. Default is no limit. * `maxHeight` Integer (optional) - Window's maximum height. Default is no limit. * `resizable` boolean (optional) - Whether window is resizable. Default is `true`. * `movable` boolean (optional) _macOS_ _Windows_ - Whether window is movable. This is not implemented on Linux. Default is `true`. * `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is minimizable. This is not implemented on Linux. Default is `true`. * `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is maximizable. This is not implemented on Linux. Default is `true`. * `closable` boolean (optional) _macOS_ _Windows_ - Whether window is closable. This is not implemented on Linux. Default is `true`. * `focusable` boolean (optional) - Whether the window can be focused. Default is `true`. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. * `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of other windows. Default is `false`. * `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. * `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. * `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on macOS. Default is `false`. * `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar. Default is `false`. * `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control. * `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`. * `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. * `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is recommended to use `ICO` icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. * `show` boolean (optional) - Whether window should be shown when created. Default is `true`. * `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`. * `frame` boolean (optional) - Specify `false` to create a [frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`. * `parent` BrowserWindow (optional) - Specify parent window. Default is `null`. * `modal` boolean (optional) - Whether this is a modal window. This only works when the window is a child window. Default is `false`. * `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an inactive window will also click through to the web contents. Default is `false` on macOS. This option is not configurable on other platforms. * `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing. Default is `false`. * `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. * `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to be resized larger than screen. Only relevant for macOS, as other OSes allow larger-than-screen windows by default. Default is `false`. * `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information. * `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`. * `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS. * `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is `false`. * `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows). Default is `false`. On Windows, does not work unless the window is frameless. * `type` string (optional) - The type of window, default is normal window. See more about this below. * `visualEffectState` string (optional) _macOS_ - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are: * `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default. * `active` - The backdrop should always appear active. * `inactive` - The backdrop should always appear inactive. * `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar. Default is `default`. Possible values are: * `default` - Results in the standard title bar for macOS or Windows respectively. * `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown. * `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. * `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden title bar and a full size content window, the traffic light buttons will display when being hovered over in the top left of the window. **Note:** This option is currently experimental. * `trafficLightPosition` [Point](point.md) (optional) _macOS_ - Set a custom position for the traffic light buttons in frameless windows. * `roundedCorners` boolean (optional) _macOS_ - Whether frameless window should have rounded corners on macOS. Default is `true`. Setting this property to `false` will prevent the window from being fullscreenable. * `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows the title in the title bar in full screen mode on macOS for `hiddenInset` titleBarStyle. Default is `false`. * `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard window frame. Setting it to `false` will remove window shadow and window animations. Default is `true`. * `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to the window, only on macOS. Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are deprecated and have been removed in macOS Catalina (10.15). * `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window will grow to the preferred width of the web page when zoomed, `false` will cause it to zoom to the width of the screen. This will also affect the behavior when calling `maximize()` directly. Default is `false`. * `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows opening the window as a native tab. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows your `app` and window to receive the `new-window-for-tab` event. * `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features. * `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`. * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color. * `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height. When setting minimum or maximum window size with `minWidth`/`maxWidth`/ `minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from passing a size that does not follow size constraints to `setBounds`/`setSize` or to the constructor of `BrowserWindow`. The possible values and behaviors of the `type` option are platform dependent. Possible values are: * On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`, `notification`. * On macOS, possible types are `desktop`, `textured`, `panel`. * The `textured` type adds metal gradient appearance (`NSWindowStyleMaskTexturedBackground`). * The `desktop` type places the window at the desktop background window level (`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive focus, keyboard or mouse events, but you can use `globalShortcut` to receive input sparingly. * The `panel` type enables the window to float on top of full-screened apps by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally reserved for NSPanel, at runtime. Also, the window will appear on all spaces (desktops). * On Windows, possible type is `toolbar`. [overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables [overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_base_window.h" #include <string> #include <utility> #include <vector> #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); #if BUILDFLAG(ENABLE_OSR) // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } #endif // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); #else args->ThrowError("enable_desktop_capturer=true to use this feature"); #endif } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { menu_.Reset(isolate, menu.ToV8()); // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end()) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->second.Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), (*first_view).second); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& views_iter : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item.second), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.second.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #include <map> #include <memory> #include <string> #include <vector> #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "gin/handle.h" #include "shell/browser/native_window.h" #include "shell/browser/native_window_observer.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/trackable_object.h" namespace electron::api { class View; class BrowserView; class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, public NativeWindowObserver { public: static gin_helper::WrappableBase* New(gin_helper::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype); base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } NativeWindow* window() const { return window_.get(); } protected: // Common constructor. BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Creating independent BaseWindow instance. BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options); ~BaseWindow() override; // TrackableObject: void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; void OnWindowClosed() override; void OnWindowEndSession() override; void OnWindowBlur() override; void OnWindowFocus() override; void OnWindowShow() override; void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; void OnWindowRestore() override; void OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) override; void OnWindowResize() override; void OnWindowResized() override; void OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; void OnWindowSheetEnd() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; void OnWindowLeaveHtmlFullScreen() override; void OnWindowAlwaysOnTopChanged() override; void OnExecuteAppCommand(const std::string& command_name) override; void OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) override; void OnNewWindowForTab() override; void OnSystemContextMenu(int x, int y, bool* prevent_default) override; #if BUILDFLAG(IS_WIN) void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override; #endif // Public APIs of NativeWindow. void SetContentView(gin::Handle<View> view); void Close(); virtual void CloseImmediately(); virtual void Focus(); virtual void Blur(); bool IsFocused(); void Show(); void ShowInactive(); void Hide(); bool IsVisible(); bool IsEnabled(); void SetEnabled(bool enable); void Maximize(); void Unmaximize(); bool IsMaximized(); void Minimize(); void Restore(); bool IsMinimized(); void SetFullScreen(bool fullscreen); bool IsFullscreen(); void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetBounds(); void SetSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetSize(); void SetContentSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetContentSize(); void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetContentBounds(); bool IsNormal(); gfx::Rect GetNormalBounds(); void SetMinimumSize(int width, int height); std::vector<int> GetMinimumSize(); void SetMaximumSize(int width, int height); std::vector<int> GetMaximumSize(); void SetSheetOffset(double offsetY, gin_helper::Arguments* args); void SetResizable(bool resizable); bool IsResizable(); void SetMovable(bool movable); void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args); void MoveTop(); bool IsMovable(); void SetMinimizable(bool minimizable); bool IsMinimizable(); void SetMaximizable(bool maximizable); bool IsMaximizable(); void SetFullScreenable(bool fullscreenable); bool IsFullScreenable(); void SetClosable(bool closable); bool IsClosable(); void SetAlwaysOnTop(bool top, gin_helper::Arguments* args); bool IsAlwaysOnTop(); void Center(); void SetPosition(int x, int y, gin_helper::Arguments* args); std::vector<int> GetPosition(); void SetTitle(const std::string& title); std::string GetTitle(); void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); void FlashFrame(bool flash); void SetSkipTaskbar(bool skip); void SetExcludedFromShownWindowsMenu(bool excluded); bool IsExcludedFromShownWindowsMenu(); void SetSimpleFullScreen(bool simple_fullscreen); bool IsSimpleFullScreen(); void SetKiosk(bool kiosk); bool IsKiosk(); bool IsTabletMode() const; virtual void SetBackgroundColor(const std::string& color_name); std::string GetBackgroundColor(gin_helper::Arguments* args); void InvalidateShadow(); void SetHasShadow(bool has_shadow); bool HasShadow(); void SetOpacity(const double opacity); double GetOpacity(); void SetShape(const std::vector<gfx::Rect>& rects); void SetRepresentedFilename(const std::string& filename); std::string GetRepresentedFilename(); void SetDocumentEdited(bool edited); bool IsDocumentEdited(); void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args); void SetContentProtection(bool enable); void SetFocusable(bool focusable); bool IsFocusable(); void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu); void RemoveMenu(); void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args); virtual void SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view); virtual void AddBrowserView(gin::Handle<BrowserView> browser_view); virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view); virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args); virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const; virtual void ResetBrowserViews(); std::string GetMediaSourceId() const; v8::Local<v8::Value> GetNativeWindowHandle(); void SetProgressBar(double progress, gin_helper::Arguments* args); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args); bool IsVisibleOnAllWorkspaces(); void SetAutoHideCursor(bool auto_hide); virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value); #if BUILDFLAG(IS_MAC) std::string GetAlwaysOnTopLevel(); void SetWindowButtonVisibility(bool visible); bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(absl::optional<gfx::Point> position); absl::optional<gfx::Point> GetWindowButtonPosition() const; #endif #if BUILDFLAG(IS_MAC) bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); void RefreshTouchBarItem(const std::string& item_id); void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); void SelectPreviousTab(); void SelectNextTab(); void MergeAllWindows(); void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide(); void SetMenuBarVisibility(bool visible); bool IsMenuBarVisible(); void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args); void PreviewFile(const std::string& path, gin_helper::Arguments* args); void CloseFilePreview(); void SetGTKDarkThemeEnabled(bool use_dark_theme); // Public getters of NativeWindow. v8::Local<v8::Value> GetContentView() const; v8::Local<v8::Value> GetParentWindow() const; std::vector<v8::Local<v8::Object>> GetChildWindows() const; v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const; bool IsModal() const; // Extra APIs added in JS. bool SetThumbarButtons(gin_helper::Arguments* args); #if defined(TOOLKIT_VIEWS) void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon); void SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error); #endif #if BUILDFLAG(IS_WIN) typedef base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)> MessageCallback; bool HookWindowMessage(UINT message, const MessageCallback& callback); bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); bool SetThumbnailClip(const gfx::Rect& region); bool SetThumbnailToolTip(const std::string& tooltip); void SetAppDetails(const gin_helper::Dictionary& options); #endif int32_t GetID() const; // Helpers. // Remove BrowserView. void ResetBrowserView(); // Remove this window from parent window's |child_windows_|. void RemoveFromParentChildWindows(); template <typename... Args> void EmitEventSoon(base::StringPiece eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), weak_factory_.GetWeakPtr(), eventName)); } #if BUILDFLAG(IS_WIN) typedef std::map<UINT, MessageCallback> MessageCallbackMap; MessageCallbackMap messages_callback_map_; #endif v8::Global<v8::Value> content_view_; std::map<int32_t, v8::Global<v8::Value>> browser_views_; v8::Global<v8::Value> menu_; v8::Global<v8::Value> parent_window_; KeyWeakMap<int> child_windows_; std::unique_ptr<NativeWindow> window_; // Reference to JS wrapper to prevent garbage collection. v8::Global<v8::Value> self_ref_; base::WeakPtrFactory<BaseWindow> weak_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (std::find(draggable_region_providers_.begin(), draggable_region_providers_.end(), provider) == draggable_region_providers_.end()) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace views { class UnhandledKeyboardEventHandler; } namespace electron { class GlobalMenuBarX11; class RootView; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); std::unique_ptr<RootView> root_view_; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/options_switches.h" namespace electron { namespace options { const char kTitle[] = "title"; const char kIcon[] = "icon"; const char kFrame[] = "frame"; const char kShow[] = "show"; const char kCenter[] = "center"; const char kX[] = "x"; const char kY[] = "y"; const char kWidth[] = "width"; const char kHeight[] = "height"; const char kMinWidth[] = "minWidth"; const char kMinHeight[] = "minHeight"; const char kMaxWidth[] = "maxWidth"; const char kMaxHeight[] = "maxHeight"; const char kResizable[] = "resizable"; const char kMovable[] = "movable"; const char kMinimizable[] = "minimizable"; const char kMaximizable[] = "maximizable"; const char kFullScreenable[] = "fullscreenable"; const char kClosable[] = "closable"; const char kFullscreen[] = "fullscreen"; const char kTrafficLightPosition[] = "trafficLightPosition"; const char kRoundedCorners[] = "roundedCorners"; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. const char kOverlayButtonColor[] = "color"; const char kOverlaySymbolColor[] = "symbolColor"; // The custom height for Window Controls Overlay. const char kOverlayHeight[] = "height"; // whether to keep the window out of mission control const char kHiddenInMissionControl[] = "hiddenInMissionControl"; // Whether the window should show in taskbar. const char kSkipTaskbar[] = "skipTaskbar"; // Start with the kiosk mode, see Opera's page for description: // http://www.opera.com/support/mastering/kiosk/ const char kKiosk[] = "kiosk"; const char kSimpleFullScreen[] = "simpleFullscreen"; // Make windows stays on the top of all other windows. const char kAlwaysOnTop[] = "alwaysOnTop"; // Enable the NSView to accept first mouse event. const char kAcceptFirstMouse[] = "acceptFirstMouse"; // Whether window size should include window frame. const char kUseContentSize[] = "useContentSize"; // Whether window zoom should be to page width. const char kZoomToPageWidth[] = "zoomToPageWidth"; // Whether always show title text in full screen is enabled. const char kFullscreenWindowTitle[] = "fullscreenWindowTitle"; // The requested title bar style for the window const char kTitleBarStyle[] = "titleBarStyle"; // Tabbing identifier for the window if native tabs are enabled on macOS. const char kTabbingIdentifier[] = "tabbingIdentifier"; // The menu bar is hidden unless "Alt" is pressed. const char kAutoHideMenuBar[] = "autoHideMenuBar"; // Enable window to be resized larger than screen. const char kEnableLargerThanScreen[] = "enableLargerThanScreen"; // Forces to use dark theme on Linux. const char kDarkTheme[] = "darkTheme"; // Whether the window should be transparent. const char kTransparent[] = "transparent"; // Window type hint. const char kType[] = "type"; // Disable auto-hiding cursor. const char kDisableAutoHideCursor[] = "disableAutoHideCursor"; // Use the macOS' standard window instead of the textured window. const char kStandardWindow[] = "standardWindow"; // Default browser window background color. const char kBackgroundColor[] = "backgroundColor"; // Whether the window should have a shadow. const char kHasShadow[] = "hasShadow"; // Browser window opacity const char kOpacity[] = "opacity"; // Whether the window can be activated. const char kFocusable[] = "focusable"; // The WebPreferences. const char kWebPreferences[] = "webPreferences"; // Add a vibrancy effect to the browser window const char kVibrancyType[] = "vibrancy"; // Specify how the material appearance should reflect window activity state on // macOS. const char kVisualEffectState[] = "visualEffectState"; // The factor of which page should be zoomed. const char kZoomFactor[] = "zoomFactor"; // Script that will be loaded by guest WebContents before other scripts. const char kPreloadScript[] = "preload"; const char kPreloadScripts[] = "preloadScripts"; // Enable the node integration. const char kNodeIntegration[] = "nodeIntegration"; // Enable context isolation of Electron APIs and preload script const char kContextIsolation[] = "contextIsolation"; // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; // Enable the rubber banding effect. const char kScrollBounce[] = "scrollBounce"; // Enable blink features. const char kEnableBlinkFeatures[] = "enableBlinkFeatures"; // Disable blink features. const char kDisableBlinkFeatures[] = "disableBlinkFeatures"; // Enable the node integration in WebWorker. const char kNodeIntegrationInWorker[] = "nodeIntegrationInWorker"; // Enable the web view tag. const char kWebviewTag[] = "webviewTag"; const char kCustomArgs[] = "additionalArguments"; const char kPlugins[] = "plugins"; const char kSandbox[] = "sandbox"; const char kWebSecurity[] = "webSecurity"; const char kAllowRunningInsecureContent[] = "allowRunningInsecureContent"; const char kOffscreen[] = "offscreen"; const char kNodeIntegrationInSubFrames[] = "nodeIntegrationInSubFrames"; // Disable window resizing when HTML Fullscreen API is activated. const char kDisableHtmlFullscreenWindowResize[] = "disableHtmlFullscreenWindowResize"; // Enables JavaScript support. const char kJavaScript[] = "javascript"; // Enables image support. const char kImages[] = "images"; // Image animation policy. const char kImageAnimationPolicy[] = "imageAnimationPolicy"; // Make TextArea elements resizable. const char kTextAreasAreResizable[] = "textAreasAreResizable"; // Enables WebGL support. const char kWebGL[] = "webgl"; // Whether dragging and dropping a file or link onto the page causes a // navigation. const char kNavigateOnDragDrop[] = "navigateOnDragDrop"; const char kHiddenPage[] = "hiddenPage"; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) const char kSpellcheck[] = "spellcheck"; #endif const char kEnableWebSQL[] = "enableWebSQL"; const char kEnablePreferredSizeMode[] = "enablePreferredSizeMode"; const char ktitleBarOverlay[] = "titleBarOverlay"; } // namespace options namespace switches { // Enable chromium sandbox. const char kEnableSandbox[] = "enable-sandbox"; // Ppapi Flash path. const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; // Disable HTTP cache. const char kDisableHttpCache[] = "disable-http-cache"; // The list of standard schemes. const char kStandardSchemes[] = "standard-schemes"; // Register schemes to handle service worker. const char kServiceWorkerSchemes[] = "service-worker-schemes"; // Register schemes as secure. const char kSecureSchemes[] = "secure-schemes"; // Register schemes as bypassing CSP. const char kBypassCSPSchemes[] = "bypasscsp-schemes"; // Register schemes as support fetch API. const char kFetchSchemes[] = "fetch-schemes"; // Register schemes as CORS enabled. const char kCORSSchemes[] = "cors-schemes"; // Register schemes as streaming responses. const char kStreamingSchemes[] = "streaming-schemes"; // The browser process app model ID const char kAppUserModelId[] = "app-user-model-id"; // The application path const char kAppPath[] = "app-path"; // The command line switch versions of the options. const char kScrollBounce[] = "scroll-bounce"; // Command switch passed to renderer process to control nodeIntegration. const char kNodeIntegrationInWorker[] = "node-integration-in-worker"; // Widevine options // Path to Widevine CDM binaries. const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; // Forces the maximum disk space to be used by the disk cache, in bytes. const char kDiskCacheSize[] = "disk-cache-size"; // Ignore the limit of 6 connections per host. const char kIgnoreConnectionsLimit[] = "ignore-connections-limit"; // Whitelist containing servers for which Integrated Authentication is enabled. const char kAuthServerWhitelist[] = "auth-server-whitelist"; // Whitelist containing servers for which Kerberos delegation is allowed. const char kAuthNegotiateDelegateWhitelist[] = "auth-negotiate-delegate-whitelist"; // If set, include the port in generated Kerberos SPNs. const char kEnableAuthNegotiatePort[] = "enable-auth-negotiate-port"; // If set, NTLM v2 is disabled for POSIX platforms. const char kDisableNTLMv2[] = "disable-ntlm-v2"; const char kEnableWebSQL[] = "enable-websql"; } // namespace switches } // namespace electron
closed
electron/electron
https://github.com/electron/electron
29,937
[Feature Request]: Use new 'Mica' material for BrowserWindow vibrancy in Windows 11
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description At the moment, [`setVibrancy()`](https://www.electronjs.org/docs/api/browser-window#winsetvibrancytype-macos) for `BrowserWindow` only supports macOS. Windows 10 has had a similar material called Acrylic, but Electron is yet to add support for it. ### Proposed Solution With Windows 11, Microsoft is introducing a more performant material dubbed Mica. From [Microsoft:](https://docs.microsoft.com/en-us/windows/apps/design/style/mica) > Mica is an opaque, dynamic material that incorporates theme and desktop wallpaper to paint the background of long-lived windows such as apps and settings. You can apply Mica to your application backdrop to delight users and create visual hierarchy, aiding productivity, by increasing clarity about which window is in focus. Mica is specifically designed for app performance as it only samples the desktop wallpaper once to create its visualization. The new Mica material is a prominent part of the Windows 11 visual design. Adding support for Mica to `setVibrancy()` in Electron would greatly elevate the design of many apps, and enable the visual look of Electron apps to be in line with modern Windows experiences. ### Alternatives Considered The following libraries currently allow apps to use Acrylic as an alternative to `vibrancy` in Windows 10: * https://github.com/Seo-Rii/electron-acrylic-window * https://github.com/AryToNeX/Glasstron ### Additional Information N/A
https://github.com/electron/electron/issues/29937
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2021-06-29T09:02:10Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #define ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #include "electron/buildflags/buildflags.h" namespace electron { namespace options { extern const char kTitle[]; extern const char kIcon[]; extern const char kFrame[]; extern const char kShow[]; extern const char kCenter[]; extern const char kX[]; extern const char kY[]; extern const char kWidth[]; extern const char kHeight[]; extern const char kMinWidth[]; extern const char kMinHeight[]; extern const char kMaxWidth[]; extern const char kMaxHeight[]; extern const char kResizable[]; extern const char kMovable[]; extern const char kMinimizable[]; extern const char kMaximizable[]; extern const char kFullScreenable[]; extern const char kClosable[]; extern const char kHiddenInMissionControl[]; extern const char kFullscreen[]; extern const char kSkipTaskbar[]; extern const char kKiosk[]; extern const char kSimpleFullScreen[]; extern const char kAlwaysOnTop[]; extern const char kAcceptFirstMouse[]; extern const char kUseContentSize[]; extern const char kZoomToPageWidth[]; extern const char kFullscreenWindowTitle[]; extern const char kTitleBarStyle[]; extern const char kTabbingIdentifier[]; extern const char kAutoHideMenuBar[]; extern const char kEnableLargerThanScreen[]; extern const char kDarkTheme[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; extern const char kStandardWindow[]; extern const char kBackgroundColor[]; extern const char kHasShadow[]; extern const char kOpacity[]; extern const char kFocusable[]; extern const char kWebPreferences[]; extern const char kVibrancyType[]; extern const char kVisualEffectState[]; extern const char kTrafficLightPosition[]; extern const char kRoundedCorners[]; extern const char ktitleBarOverlay[]; extern const char kOverlayButtonColor[]; extern const char kOverlaySymbolColor[]; extern const char kOverlayHeight[]; // WebPreferences. extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadScripts[]; extern const char kNodeIntegration[]; extern const char kContextIsolation[]; extern const char kExperimentalFeatures[]; extern const char kScrollBounce[]; extern const char kEnableBlinkFeatures[]; extern const char kDisableBlinkFeatures[]; extern const char kNodeIntegrationInWorker[]; extern const char kWebviewTag[]; extern const char kCustomArgs[]; extern const char kPlugins[]; extern const char kSandbox[]; extern const char kWebSecurity[]; extern const char kAllowRunningInsecureContent[]; extern const char kOffscreen[]; extern const char kNodeIntegrationInSubFrames[]; extern const char kDisableHtmlFullscreenWindowResize[]; extern const char kJavaScript[]; extern const char kImages[]; extern const char kImageAnimationPolicy[]; extern const char kTextAreasAreResizable[]; extern const char kWebGL[]; extern const char kNavigateOnDragDrop[]; extern const char kEnableWebSQL[]; extern const char kEnablePreferredSizeMode[]; extern const char kHiddenPage[]; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) extern const char kSpellcheck[]; #endif } // namespace options // Following are actually command line switches, should be moved to other files. namespace switches { extern const char kEnableSandbox[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; extern const char kDisableHttpCache[]; extern const char kStandardSchemes[]; extern const char kServiceWorkerSchemes[]; extern const char kSecureSchemes[]; extern const char kBypassCSPSchemes[]; extern const char kFetchSchemes[]; extern const char kCORSSchemes[]; extern const char kStreamingSchemes[]; extern const char kAppUserModelId[]; extern const char kAppPath[]; extern const char kScrollBounce[]; extern const char kNodeIntegrationInWorker[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; extern const char kDiskCacheSize[]; extern const char kIgnoreConnectionsLimit[]; extern const char kAuthServerWhitelist[]; extern const char kAuthNegotiateDelegateWhitelist[]; extern const char kEnableAuthNegotiatePort[]; extern const char kDisableNTLMv2[]; extern const char kEnableWebSQL[]; } // namespace switches } // namespace electron #endif // ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been deprecated and will be removed in an upcoming version of macOS. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - an array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
docs/api/structures/browser-window-options.md
# BrowserWindowConstructorOptions Object * `width` Integer (optional) - Window's width in pixels. Default is `800`. * `height` Integer (optional) - Window's height in pixels. Default is `600`. * `x` Integer (optional) - (**required** if y is used) Window's left offset from screen. Default is to center the window. * `y` Integer (optional) - (**required** if x is used) Window's top offset from screen. Default is to center the window. * `useContentSize` boolean (optional) - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. * `center` boolean (optional) - Show window in the center of the screen. Default is `false`. * `minWidth` Integer (optional) - Window's minimum width. Default is `0`. * `minHeight` Integer (optional) - Window's minimum height. Default is `0`. * `maxWidth` Integer (optional) - Window's maximum width. Default is no limit. * `maxHeight` Integer (optional) - Window's maximum height. Default is no limit. * `resizable` boolean (optional) - Whether window is resizable. Default is `true`. * `movable` boolean (optional) _macOS_ _Windows_ - Whether window is movable. This is not implemented on Linux. Default is `true`. * `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is minimizable. This is not implemented on Linux. Default is `true`. * `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is maximizable. This is not implemented on Linux. Default is `true`. * `closable` boolean (optional) _macOS_ _Windows_ - Whether window is closable. This is not implemented on Linux. Default is `true`. * `focusable` boolean (optional) - Whether the window can be focused. Default is `true`. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. * `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of other windows. Default is `false`. * `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. * `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. * `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on macOS. Default is `false`. * `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar. Default is `false`. * `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control. * `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`. * `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. * `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is recommended to use `ICO` icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. * `show` boolean (optional) - Whether window should be shown when created. Default is `true`. * `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`. * `frame` boolean (optional) - Specify `false` to create a [frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`. * `parent` BrowserWindow (optional) - Specify parent window. Default is `null`. * `modal` boolean (optional) - Whether this is a modal window. This only works when the window is a child window. Default is `false`. * `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an inactive window will also click through to the web contents. Default is `false` on macOS. This option is not configurable on other platforms. * `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing. Default is `false`. * `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. * `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to be resized larger than screen. Only relevant for macOS, as other OSes allow larger-than-screen windows by default. Default is `false`. * `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information. * `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`. * `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS. * `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is `false`. * `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows). Default is `false`. On Windows, does not work unless the window is frameless. * `type` string (optional) - The type of window, default is normal window. See more about this below. * `visualEffectState` string (optional) _macOS_ - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are: * `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default. * `active` - The backdrop should always appear active. * `inactive` - The backdrop should always appear inactive. * `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar. Default is `default`. Possible values are: * `default` - Results in the standard title bar for macOS or Windows respectively. * `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown. * `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge. * `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden title bar and a full size content window, the traffic light buttons will display when being hovered over in the top left of the window. **Note:** This option is currently experimental. * `trafficLightPosition` [Point](point.md) (optional) _macOS_ - Set a custom position for the traffic light buttons in frameless windows. * `roundedCorners` boolean (optional) _macOS_ - Whether frameless window should have rounded corners on macOS. Default is `true`. Setting this property to `false` will prevent the window from being fullscreenable. * `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows the title in the title bar in full screen mode on macOS for `hiddenInset` titleBarStyle. Default is `false`. * `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard window frame. Setting it to `false` will remove window shadow and window animations. Default is `true`. * `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to the window, only on macOS. Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are deprecated and have been removed in macOS Catalina (10.15). * `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window will grow to the preferred width of the web page when zoomed, `false` will cause it to zoom to the width of the screen. This will also affect the behavior when calling `maximize()` directly. Default is `false`. * `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows opening the window as a native tab. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows your `app` and window to receive the `new-window-for-tab` event. * `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features. * `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`. * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color. * `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height. When setting minimum or maximum window size with `minWidth`/`maxWidth`/ `minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from passing a size that does not follow size constraints to `setBounds`/`setSize` or to the constructor of `BrowserWindow`. The possible values and behaviors of the `type` option are platform dependent. Possible values are: * On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`, `notification`. * On macOS, possible types are `desktop`, `textured`, `panel`. * The `textured` type adds metal gradient appearance (`NSWindowStyleMaskTexturedBackground`). * The `desktop` type places the window at the desktop background window level (`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive focus, keyboard or mouse events, but you can use `globalShortcut` to receive input sparingly. * The `panel` type enables the window to float on top of full-screened apps by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally reserved for NSPanel, at runtime. Also, the window will appear on all spaces (desktops). * On Windows, possible type is `toolbar`. [overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables [overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_base_window.h" #include <string> #include <utility> #include <vector> #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); #if BUILDFLAG(ENABLE_OSR) // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } #endif // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); #else args->ThrowError("enable_desktop_capturer=true to use this feature"); #endif } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { menu_.Reset(isolate, menu.ToV8()); // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end()) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = browser_views_.find(browser_view->ID()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->second.Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = browser_views_.find(browser_view->ID()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), (*first_view).second); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& views_iter : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item.second), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.second.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/api/electron_api_base_window.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_ #include <map> #include <memory> #include <string> #include <vector> #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "gin/handle.h" #include "shell/browser/native_window.h" #include "shell/browser/native_window_observer.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/trackable_object.h" namespace electron::api { class View; class BrowserView; class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, public NativeWindowObserver { public: static gin_helper::WrappableBase* New(gin_helper::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype); base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } NativeWindow* window() const { return window_.get(); } protected: // Common constructor. BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Creating independent BaseWindow instance. BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options); ~BaseWindow() override; // TrackableObject: void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; void OnWindowClosed() override; void OnWindowEndSession() override; void OnWindowBlur() override; void OnWindowFocus() override; void OnWindowShow() override; void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; void OnWindowRestore() override; void OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) override; void OnWindowResize() override; void OnWindowResized() override; void OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; void OnWindowSheetEnd() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; void OnWindowLeaveHtmlFullScreen() override; void OnWindowAlwaysOnTopChanged() override; void OnExecuteAppCommand(const std::string& command_name) override; void OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) override; void OnNewWindowForTab() override; void OnSystemContextMenu(int x, int y, bool* prevent_default) override; #if BUILDFLAG(IS_WIN) void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override; #endif // Public APIs of NativeWindow. void SetContentView(gin::Handle<View> view); void Close(); virtual void CloseImmediately(); virtual void Focus(); virtual void Blur(); bool IsFocused(); void Show(); void ShowInactive(); void Hide(); bool IsVisible(); bool IsEnabled(); void SetEnabled(bool enable); void Maximize(); void Unmaximize(); bool IsMaximized(); void Minimize(); void Restore(); bool IsMinimized(); void SetFullScreen(bool fullscreen); bool IsFullscreen(); void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetBounds(); void SetSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetSize(); void SetContentSize(int width, int height, gin_helper::Arguments* args); std::vector<int> GetContentSize(); void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args); gfx::Rect GetContentBounds(); bool IsNormal(); gfx::Rect GetNormalBounds(); void SetMinimumSize(int width, int height); std::vector<int> GetMinimumSize(); void SetMaximumSize(int width, int height); std::vector<int> GetMaximumSize(); void SetSheetOffset(double offsetY, gin_helper::Arguments* args); void SetResizable(bool resizable); bool IsResizable(); void SetMovable(bool movable); void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args); void MoveTop(); bool IsMovable(); void SetMinimizable(bool minimizable); bool IsMinimizable(); void SetMaximizable(bool maximizable); bool IsMaximizable(); void SetFullScreenable(bool fullscreenable); bool IsFullScreenable(); void SetClosable(bool closable); bool IsClosable(); void SetAlwaysOnTop(bool top, gin_helper::Arguments* args); bool IsAlwaysOnTop(); void Center(); void SetPosition(int x, int y, gin_helper::Arguments* args); std::vector<int> GetPosition(); void SetTitle(const std::string& title); std::string GetTitle(); void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); void FlashFrame(bool flash); void SetSkipTaskbar(bool skip); void SetExcludedFromShownWindowsMenu(bool excluded); bool IsExcludedFromShownWindowsMenu(); void SetSimpleFullScreen(bool simple_fullscreen); bool IsSimpleFullScreen(); void SetKiosk(bool kiosk); bool IsKiosk(); bool IsTabletMode() const; virtual void SetBackgroundColor(const std::string& color_name); std::string GetBackgroundColor(gin_helper::Arguments* args); void InvalidateShadow(); void SetHasShadow(bool has_shadow); bool HasShadow(); void SetOpacity(const double opacity); double GetOpacity(); void SetShape(const std::vector<gfx::Rect>& rects); void SetRepresentedFilename(const std::string& filename); std::string GetRepresentedFilename(); void SetDocumentEdited(bool edited); bool IsDocumentEdited(); void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args); void SetContentProtection(bool enable); void SetFocusable(bool focusable); bool IsFocusable(); void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu); void RemoveMenu(); void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args); virtual void SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view); virtual void AddBrowserView(gin::Handle<BrowserView> browser_view); virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view); virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args); virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const; virtual void ResetBrowserViews(); std::string GetMediaSourceId() const; v8::Local<v8::Value> GetNativeWindowHandle(); void SetProgressBar(double progress, gin_helper::Arguments* args); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args); bool IsVisibleOnAllWorkspaces(); void SetAutoHideCursor(bool auto_hide); virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value); #if BUILDFLAG(IS_MAC) std::string GetAlwaysOnTopLevel(); void SetWindowButtonVisibility(bool visible); bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(absl::optional<gfx::Point> position); absl::optional<gfx::Point> GetWindowButtonPosition() const; #endif #if BUILDFLAG(IS_MAC) bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); void RefreshTouchBarItem(const std::string& item_id); void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); void SelectPreviousTab(); void SelectNextTab(); void MergeAllWindows(); void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide(); void SetMenuBarVisibility(bool visible); bool IsMenuBarVisible(); void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args); void PreviewFile(const std::string& path, gin_helper::Arguments* args); void CloseFilePreview(); void SetGTKDarkThemeEnabled(bool use_dark_theme); // Public getters of NativeWindow. v8::Local<v8::Value> GetContentView() const; v8::Local<v8::Value> GetParentWindow() const; std::vector<v8::Local<v8::Object>> GetChildWindows() const; v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const; bool IsModal() const; // Extra APIs added in JS. bool SetThumbarButtons(gin_helper::Arguments* args); #if defined(TOOLKIT_VIEWS) void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon); void SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error); #endif #if BUILDFLAG(IS_WIN) typedef base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)> MessageCallback; bool HookWindowMessage(UINT message, const MessageCallback& callback); bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); bool SetThumbnailClip(const gfx::Rect& region); bool SetThumbnailToolTip(const std::string& tooltip); void SetAppDetails(const gin_helper::Dictionary& options); #endif int32_t GetID() const; // Helpers. // Remove BrowserView. void ResetBrowserView(); // Remove this window from parent window's |child_windows_|. void RemoveFromParentChildWindows(); template <typename... Args> void EmitEventSoon(base::StringPiece eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), weak_factory_.GetWeakPtr(), eventName)); } #if BUILDFLAG(IS_WIN) typedef std::map<UINT, MessageCallback> MessageCallbackMap; MessageCallbackMap messages_callback_map_; #endif v8::Global<v8::Value> content_view_; std::map<int32_t, v8::Global<v8::Value>> browser_views_; v8::Global<v8::Value> menu_; v8::Global<v8::Value> parent_window_; KeyWeakMap<int> child_windows_; std::unique_ptr<NativeWindow> window_; // Reference to JS wrapper to prevent garbage collection. v8::Global<v8::Value> self_ref_; base::WeakPtrFactory<BaseWindow> weak_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (std::find(draggable_region_providers_.begin(), draggable_region_providers_.end(), provider) == draggable_region_providers_.end()) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/browser/native_window_views.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace views { class UnhandledKeyboardEventHandler; } namespace electron { class GlobalMenuBarX11; class RootView; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); std::unique_ptr<RootView> root_view_; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/options_switches.h" namespace electron { namespace options { const char kTitle[] = "title"; const char kIcon[] = "icon"; const char kFrame[] = "frame"; const char kShow[] = "show"; const char kCenter[] = "center"; const char kX[] = "x"; const char kY[] = "y"; const char kWidth[] = "width"; const char kHeight[] = "height"; const char kMinWidth[] = "minWidth"; const char kMinHeight[] = "minHeight"; const char kMaxWidth[] = "maxWidth"; const char kMaxHeight[] = "maxHeight"; const char kResizable[] = "resizable"; const char kMovable[] = "movable"; const char kMinimizable[] = "minimizable"; const char kMaximizable[] = "maximizable"; const char kFullScreenable[] = "fullscreenable"; const char kClosable[] = "closable"; const char kFullscreen[] = "fullscreen"; const char kTrafficLightPosition[] = "trafficLightPosition"; const char kRoundedCorners[] = "roundedCorners"; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. const char kOverlayButtonColor[] = "color"; const char kOverlaySymbolColor[] = "symbolColor"; // The custom height for Window Controls Overlay. const char kOverlayHeight[] = "height"; // whether to keep the window out of mission control const char kHiddenInMissionControl[] = "hiddenInMissionControl"; // Whether the window should show in taskbar. const char kSkipTaskbar[] = "skipTaskbar"; // Start with the kiosk mode, see Opera's page for description: // http://www.opera.com/support/mastering/kiosk/ const char kKiosk[] = "kiosk"; const char kSimpleFullScreen[] = "simpleFullscreen"; // Make windows stays on the top of all other windows. const char kAlwaysOnTop[] = "alwaysOnTop"; // Enable the NSView to accept first mouse event. const char kAcceptFirstMouse[] = "acceptFirstMouse"; // Whether window size should include window frame. const char kUseContentSize[] = "useContentSize"; // Whether window zoom should be to page width. const char kZoomToPageWidth[] = "zoomToPageWidth"; // Whether always show title text in full screen is enabled. const char kFullscreenWindowTitle[] = "fullscreenWindowTitle"; // The requested title bar style for the window const char kTitleBarStyle[] = "titleBarStyle"; // Tabbing identifier for the window if native tabs are enabled on macOS. const char kTabbingIdentifier[] = "tabbingIdentifier"; // The menu bar is hidden unless "Alt" is pressed. const char kAutoHideMenuBar[] = "autoHideMenuBar"; // Enable window to be resized larger than screen. const char kEnableLargerThanScreen[] = "enableLargerThanScreen"; // Forces to use dark theme on Linux. const char kDarkTheme[] = "darkTheme"; // Whether the window should be transparent. const char kTransparent[] = "transparent"; // Window type hint. const char kType[] = "type"; // Disable auto-hiding cursor. const char kDisableAutoHideCursor[] = "disableAutoHideCursor"; // Use the macOS' standard window instead of the textured window. const char kStandardWindow[] = "standardWindow"; // Default browser window background color. const char kBackgroundColor[] = "backgroundColor"; // Whether the window should have a shadow. const char kHasShadow[] = "hasShadow"; // Browser window opacity const char kOpacity[] = "opacity"; // Whether the window can be activated. const char kFocusable[] = "focusable"; // The WebPreferences. const char kWebPreferences[] = "webPreferences"; // Add a vibrancy effect to the browser window const char kVibrancyType[] = "vibrancy"; // Specify how the material appearance should reflect window activity state on // macOS. const char kVisualEffectState[] = "visualEffectState"; // The factor of which page should be zoomed. const char kZoomFactor[] = "zoomFactor"; // Script that will be loaded by guest WebContents before other scripts. const char kPreloadScript[] = "preload"; const char kPreloadScripts[] = "preloadScripts"; // Enable the node integration. const char kNodeIntegration[] = "nodeIntegration"; // Enable context isolation of Electron APIs and preload script const char kContextIsolation[] = "contextIsolation"; // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; // Enable the rubber banding effect. const char kScrollBounce[] = "scrollBounce"; // Enable blink features. const char kEnableBlinkFeatures[] = "enableBlinkFeatures"; // Disable blink features. const char kDisableBlinkFeatures[] = "disableBlinkFeatures"; // Enable the node integration in WebWorker. const char kNodeIntegrationInWorker[] = "nodeIntegrationInWorker"; // Enable the web view tag. const char kWebviewTag[] = "webviewTag"; const char kCustomArgs[] = "additionalArguments"; const char kPlugins[] = "plugins"; const char kSandbox[] = "sandbox"; const char kWebSecurity[] = "webSecurity"; const char kAllowRunningInsecureContent[] = "allowRunningInsecureContent"; const char kOffscreen[] = "offscreen"; const char kNodeIntegrationInSubFrames[] = "nodeIntegrationInSubFrames"; // Disable window resizing when HTML Fullscreen API is activated. const char kDisableHtmlFullscreenWindowResize[] = "disableHtmlFullscreenWindowResize"; // Enables JavaScript support. const char kJavaScript[] = "javascript"; // Enables image support. const char kImages[] = "images"; // Image animation policy. const char kImageAnimationPolicy[] = "imageAnimationPolicy"; // Make TextArea elements resizable. const char kTextAreasAreResizable[] = "textAreasAreResizable"; // Enables WebGL support. const char kWebGL[] = "webgl"; // Whether dragging and dropping a file or link onto the page causes a // navigation. const char kNavigateOnDragDrop[] = "navigateOnDragDrop"; const char kHiddenPage[] = "hiddenPage"; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) const char kSpellcheck[] = "spellcheck"; #endif const char kEnableWebSQL[] = "enableWebSQL"; const char kEnablePreferredSizeMode[] = "enablePreferredSizeMode"; const char ktitleBarOverlay[] = "titleBarOverlay"; } // namespace options namespace switches { // Enable chromium sandbox. const char kEnableSandbox[] = "enable-sandbox"; // Ppapi Flash path. const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; // Disable HTTP cache. const char kDisableHttpCache[] = "disable-http-cache"; // The list of standard schemes. const char kStandardSchemes[] = "standard-schemes"; // Register schemes to handle service worker. const char kServiceWorkerSchemes[] = "service-worker-schemes"; // Register schemes as secure. const char kSecureSchemes[] = "secure-schemes"; // Register schemes as bypassing CSP. const char kBypassCSPSchemes[] = "bypasscsp-schemes"; // Register schemes as support fetch API. const char kFetchSchemes[] = "fetch-schemes"; // Register schemes as CORS enabled. const char kCORSSchemes[] = "cors-schemes"; // Register schemes as streaming responses. const char kStreamingSchemes[] = "streaming-schemes"; // The browser process app model ID const char kAppUserModelId[] = "app-user-model-id"; // The application path const char kAppPath[] = "app-path"; // The command line switch versions of the options. const char kScrollBounce[] = "scroll-bounce"; // Command switch passed to renderer process to control nodeIntegration. const char kNodeIntegrationInWorker[] = "node-integration-in-worker"; // Widevine options // Path to Widevine CDM binaries. const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; // Forces the maximum disk space to be used by the disk cache, in bytes. const char kDiskCacheSize[] = "disk-cache-size"; // Ignore the limit of 6 connections per host. const char kIgnoreConnectionsLimit[] = "ignore-connections-limit"; // Whitelist containing servers for which Integrated Authentication is enabled. const char kAuthServerWhitelist[] = "auth-server-whitelist"; // Whitelist containing servers for which Kerberos delegation is allowed. const char kAuthNegotiateDelegateWhitelist[] = "auth-negotiate-delegate-whitelist"; // If set, include the port in generated Kerberos SPNs. const char kEnableAuthNegotiatePort[] = "enable-auth-negotiate-port"; // If set, NTLM v2 is disabled for POSIX platforms. const char kDisableNTLMv2[] = "disable-ntlm-v2"; const char kEnableWebSQL[] = "enable-websql"; } // namespace switches } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,391
Vibrancy Support for Windows
**Is your feature request related to a problem? Please describe.** MacOS has support for the `vibrancy` field, there's been quite a few Windows versions, yet there's still no official support in Electron. **Describe the solution you'd like** An official Windows solution to vibrancy, using acrylic or any other background blurring method. **Describe alternatives you've considered** https://github.com/arkenthera/electron-vibrancy https://github.com/23phy/electron-acrylic https://github.com/sylveon/windows-blurbehind All require a lower version of Electron than 4.0, and/or to be building on Windows.
https://github.com/electron/electron/issues/16391
https://github.com/electron/electron/pull/38163
c2d7164021011df7c31bbc09f824311535323793
e19500fa03bf08af1466dac5dbca39f1b4281d9c
2019-01-14T13:32:33Z
c++
2023-05-15T20:31:57Z
shell/common/options_switches.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #define ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_ #include "electron/buildflags/buildflags.h" namespace electron { namespace options { extern const char kTitle[]; extern const char kIcon[]; extern const char kFrame[]; extern const char kShow[]; extern const char kCenter[]; extern const char kX[]; extern const char kY[]; extern const char kWidth[]; extern const char kHeight[]; extern const char kMinWidth[]; extern const char kMinHeight[]; extern const char kMaxWidth[]; extern const char kMaxHeight[]; extern const char kResizable[]; extern const char kMovable[]; extern const char kMinimizable[]; extern const char kMaximizable[]; extern const char kFullScreenable[]; extern const char kClosable[]; extern const char kHiddenInMissionControl[]; extern const char kFullscreen[]; extern const char kSkipTaskbar[]; extern const char kKiosk[]; extern const char kSimpleFullScreen[]; extern const char kAlwaysOnTop[]; extern const char kAcceptFirstMouse[]; extern const char kUseContentSize[]; extern const char kZoomToPageWidth[]; extern const char kFullscreenWindowTitle[]; extern const char kTitleBarStyle[]; extern const char kTabbingIdentifier[]; extern const char kAutoHideMenuBar[]; extern const char kEnableLargerThanScreen[]; extern const char kDarkTheme[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; extern const char kStandardWindow[]; extern const char kBackgroundColor[]; extern const char kHasShadow[]; extern const char kOpacity[]; extern const char kFocusable[]; extern const char kWebPreferences[]; extern const char kVibrancyType[]; extern const char kVisualEffectState[]; extern const char kTrafficLightPosition[]; extern const char kRoundedCorners[]; extern const char ktitleBarOverlay[]; extern const char kOverlayButtonColor[]; extern const char kOverlaySymbolColor[]; extern const char kOverlayHeight[]; // WebPreferences. extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadScripts[]; extern const char kNodeIntegration[]; extern const char kContextIsolation[]; extern const char kExperimentalFeatures[]; extern const char kScrollBounce[]; extern const char kEnableBlinkFeatures[]; extern const char kDisableBlinkFeatures[]; extern const char kNodeIntegrationInWorker[]; extern const char kWebviewTag[]; extern const char kCustomArgs[]; extern const char kPlugins[]; extern const char kSandbox[]; extern const char kWebSecurity[]; extern const char kAllowRunningInsecureContent[]; extern const char kOffscreen[]; extern const char kNodeIntegrationInSubFrames[]; extern const char kDisableHtmlFullscreenWindowResize[]; extern const char kJavaScript[]; extern const char kImages[]; extern const char kImageAnimationPolicy[]; extern const char kTextAreasAreResizable[]; extern const char kWebGL[]; extern const char kNavigateOnDragDrop[]; extern const char kEnableWebSQL[]; extern const char kEnablePreferredSizeMode[]; extern const char kHiddenPage[]; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) extern const char kSpellcheck[]; #endif } // namespace options // Following are actually command line switches, should be moved to other files. namespace switches { extern const char kEnableSandbox[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; extern const char kDisableHttpCache[]; extern const char kStandardSchemes[]; extern const char kServiceWorkerSchemes[]; extern const char kSecureSchemes[]; extern const char kBypassCSPSchemes[]; extern const char kFetchSchemes[]; extern const char kCORSSchemes[]; extern const char kStreamingSchemes[]; extern const char kAppUserModelId[]; extern const char kAppPath[]; extern const char kScrollBounce[]; extern const char kNodeIntegrationInWorker[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; extern const char kDiskCacheSize[]; extern const char kIgnoreConnectionsLimit[]; extern const char kAuthServerWhitelist[]; extern const char kAuthNegotiateDelegateWhitelist[]; extern const char kEnableAuthNegotiatePort[]; extern const char kDisableNTLMv2[]; extern const char kEnableWebSQL[]; } // namespace switches } // namespace electron #endif // ELECTRON_SHELL_COMMON_OPTIONS_SWITCHES_H_
closed
electron/electron
https://github.com/electron/electron
38,170
[Bug]: Accessing `BrowserWindow.id` throws an error after the window is closed/destroyed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I want to get the `id` of a `BrowserWindow` object, regardless of whether or not it is closed or destroyed. I expect the following to work: ``` win.on('closed', () => { console.log('window closed, id=', win.id); } ``` ### Actual Behavior It throws an error: ``` TypeError: Object has been destroyed at BrowserWindow.<anonymous> (**/main.js:20:60) at BrowserWindow.emit (node:events:513:28) ``` ### Testcase Gist URL https://gist.github.com/d1819a38f1a9327ae56d4098b9d382d1 ### Additional Information _No response_
https://github.com/electron/electron/issues/38170
https://github.com/electron/electron/pull/38241
042663e19058cebc83428a5a354b863d2bb10e31
9bd9d312f8d59d3a80defba4aeb760e2c3e7e10c
2023-05-03T23:06:01Z
c++
2023-05-16T07:29:00Z
lib/browser/api/browser-window.ts
import { BaseWindow, WebContents, BrowserView, TouchBar } from 'electron/main'; import type { BrowserWindow as BWT } from 'electron/main'; import * as deprecate from '@electron/internal/common/deprecate'; const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT }; Object.setPrototypeOf(BrowserWindow.prototype, BaseWindow.prototype); BrowserWindow.prototype._init = function (this: BWT) { // Call parent class's _init. BaseWindow.prototype._init.call(this); // Avoid recursive require. const { app } = require('electron'); const nativeSetBounds = this.setBounds; this.setBounds = (bounds, ...opts) => { bounds = { ...this.getBounds(), ...bounds }; nativeSetBounds.call(this, bounds, ...opts); }; // Redirect focus/blur event to app instance too. this.on('blur', (event: Electron.Event) => { app.emit('browser-window-blur', event, this); }); this.on('focus', (event: Electron.Event) => { app.emit('browser-window-focus', event, this); }); // Subscribe to visibilityState changes and pass to renderer process. let isVisible = this.isVisible() && !this.isMinimized(); const visibilityChanged = () => { const newState = this.isVisible() && !this.isMinimized(); if (isVisible !== newState) { isVisible = newState; const visibilityState = isVisible ? 'visible' : 'hidden'; this.webContents.emit('-window-visibility-change', visibilityState); } }; const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore']; for (const event of visibilityEvents) { this.on(event as any, visibilityChanged); } const warn = deprecate.warnOnceMessage('\'scroll-touch-{begin,end,edge}\' are deprecated and will be removed. Please use the WebContents \'input-event\' event instead.'); this.webContents.on('input-event', (_, e) => { if (e.type === 'gestureScrollBegin') { if (this.listenerCount('scroll-touch-begin') !== 0) { warn(); this.emit('scroll-touch-edge'); this.emit('scroll-touch-begin'); } } else if (e.type === 'gestureScrollUpdate') { if (this.listenerCount('scroll-touch-edge') !== 0) { warn(); this.emit('scroll-touch-edge'); } } else if (e.type === 'gestureScrollEnd') { if (this.listenerCount('scroll-touch-end') !== 0) { warn(); this.emit('scroll-touch-edge'); this.emit('scroll-touch-end'); } } }); // Notify the creation of the window. app.emit('browser-window-created', { preventDefault () {} }, this); Object.defineProperty(this, 'devToolsWebContents', { enumerable: true, configurable: false, get () { return this.webContents.devToolsWebContents; } }); }; const isBrowserWindow = (win: any) => { return win && win.constructor.name === 'BrowserWindow'; }; BrowserWindow.fromId = (id: number) => { const win = BaseWindow.fromId(id); return isBrowserWindow(win) ? win as any as BWT : null; }; BrowserWindow.getAllWindows = () => { return BaseWindow.getAllWindows().filter(isBrowserWindow) as any[] as BWT[]; }; BrowserWindow.getFocusedWindow = () => { for (const window of BrowserWindow.getAllWindows()) { if (!window.isDestroyed() && window.webContents && !window.webContents.isDestroyed()) { if (window.isFocused() || window.webContents.isDevToolsFocused()) return window; } } return null; }; BrowserWindow.fromWebContents = (webContents: WebContents) => { return webContents.getOwnerBrowserWindow(); }; BrowserWindow.fromBrowserView = (browserView: BrowserView) => { return BrowserWindow.fromWebContents(browserView.webContents); }; BrowserWindow.prototype.setTouchBar = function (touchBar) { (TouchBar as any)._setOnWindow(touchBar, this); }; // Forwarded to webContents: BrowserWindow.prototype.loadURL = function (...args) { return this.webContents.loadURL(...args); }; BrowserWindow.prototype.getURL = function () { return this.webContents.getURL(); }; BrowserWindow.prototype.loadFile = function (...args) { return this.webContents.loadFile(...args); }; BrowserWindow.prototype.reload = function (...args) { return this.webContents.reload(...args); }; BrowserWindow.prototype.send = function (...args) { return this.webContents.send(...args); }; BrowserWindow.prototype.openDevTools = function (...args) { return this.webContents.openDevTools(...args); }; BrowserWindow.prototype.closeDevTools = function () { return this.webContents.closeDevTools(); }; BrowserWindow.prototype.isDevToolsOpened = function () { return this.webContents.isDevToolsOpened(); }; BrowserWindow.prototype.isDevToolsFocused = function () { return this.webContents.isDevToolsFocused(); }; BrowserWindow.prototype.toggleDevTools = function () { return this.webContents.toggleDevTools(); }; BrowserWindow.prototype.inspectElement = function (...args) { return this.webContents.inspectElement(...args); }; BrowserWindow.prototype.inspectSharedWorker = function () { return this.webContents.inspectSharedWorker(); }; BrowserWindow.prototype.inspectServiceWorker = function () { return this.webContents.inspectServiceWorker(); }; BrowserWindow.prototype.showDefinitionForSelection = function () { return this.webContents.showDefinitionForSelection(); }; BrowserWindow.prototype.capturePage = function (...args) { return this.webContents.capturePage(...args); }; BrowserWindow.prototype.getBackgroundThrottling = function () { return this.webContents.getBackgroundThrottling(); }; BrowserWindow.prototype.setBackgroundThrottling = function (allowed: boolean) { return this.webContents.setBackgroundThrottling(allowed); }; module.exports = BrowserWindow;
closed
electron/electron
https://github.com/electron/electron
38,170
[Bug]: Accessing `BrowserWindow.id` throws an error after the window is closed/destroyed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I want to get the `id` of a `BrowserWindow` object, regardless of whether or not it is closed or destroyed. I expect the following to work: ``` win.on('closed', () => { console.log('window closed, id=', win.id); } ``` ### Actual Behavior It throws an error: ``` TypeError: Object has been destroyed at BrowserWindow.<anonymous> (**/main.js:20:60) at BrowserWindow.emit (node:events:513:28) ``` ### Testcase Gist URL https://gist.github.com/d1819a38f1a9327ae56d4098b9d382d1 ### Additional Information _No response_
https://github.com/electron/electron/issues/38170
https://github.com/electron/electron/pull/38241
042663e19058cebc83428a5a354b863d2bb10e31
9bd9d312f8d59d3a80defba4aeb760e2c3e7e10c
2023-05-03T23:06:01Z
c++
2023-05-16T07:29:00Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,170
[Bug]: Accessing `BrowserWindow.id` throws an error after the window is closed/destroyed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I want to get the `id` of a `BrowserWindow` object, regardless of whether or not it is closed or destroyed. I expect the following to work: ``` win.on('closed', () => { console.log('window closed, id=', win.id); } ``` ### Actual Behavior It throws an error: ``` TypeError: Object has been destroyed at BrowserWindow.<anonymous> (**/main.js:20:60) at BrowserWindow.emit (node:events:513:28) ``` ### Testcase Gist URL https://gist.github.com/d1819a38f1a9327ae56d4098b9d382d1 ### Additional Information _No response_
https://github.com/electron/electron/issues/38170
https://github.com/electron/electron/pull/38241
042663e19058cebc83428a5a354b863d2bb10e31
9bd9d312f8d59d3a80defba4aeb760e2c3e7e10c
2023-05-03T23:06:01Z
c++
2023-05-16T07:29:00Z
lib/browser/api/browser-window.ts
import { BaseWindow, WebContents, BrowserView, TouchBar } from 'electron/main'; import type { BrowserWindow as BWT } from 'electron/main'; import * as deprecate from '@electron/internal/common/deprecate'; const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT }; Object.setPrototypeOf(BrowserWindow.prototype, BaseWindow.prototype); BrowserWindow.prototype._init = function (this: BWT) { // Call parent class's _init. BaseWindow.prototype._init.call(this); // Avoid recursive require. const { app } = require('electron'); const nativeSetBounds = this.setBounds; this.setBounds = (bounds, ...opts) => { bounds = { ...this.getBounds(), ...bounds }; nativeSetBounds.call(this, bounds, ...opts); }; // Redirect focus/blur event to app instance too. this.on('blur', (event: Electron.Event) => { app.emit('browser-window-blur', event, this); }); this.on('focus', (event: Electron.Event) => { app.emit('browser-window-focus', event, this); }); // Subscribe to visibilityState changes and pass to renderer process. let isVisible = this.isVisible() && !this.isMinimized(); const visibilityChanged = () => { const newState = this.isVisible() && !this.isMinimized(); if (isVisible !== newState) { isVisible = newState; const visibilityState = isVisible ? 'visible' : 'hidden'; this.webContents.emit('-window-visibility-change', visibilityState); } }; const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore']; for (const event of visibilityEvents) { this.on(event as any, visibilityChanged); } const warn = deprecate.warnOnceMessage('\'scroll-touch-{begin,end,edge}\' are deprecated and will be removed. Please use the WebContents \'input-event\' event instead.'); this.webContents.on('input-event', (_, e) => { if (e.type === 'gestureScrollBegin') { if (this.listenerCount('scroll-touch-begin') !== 0) { warn(); this.emit('scroll-touch-edge'); this.emit('scroll-touch-begin'); } } else if (e.type === 'gestureScrollUpdate') { if (this.listenerCount('scroll-touch-edge') !== 0) { warn(); this.emit('scroll-touch-edge'); } } else if (e.type === 'gestureScrollEnd') { if (this.listenerCount('scroll-touch-end') !== 0) { warn(); this.emit('scroll-touch-edge'); this.emit('scroll-touch-end'); } } }); // Notify the creation of the window. app.emit('browser-window-created', { preventDefault () {} }, this); Object.defineProperty(this, 'devToolsWebContents', { enumerable: true, configurable: false, get () { return this.webContents.devToolsWebContents; } }); }; const isBrowserWindow = (win: any) => { return win && win.constructor.name === 'BrowserWindow'; }; BrowserWindow.fromId = (id: number) => { const win = BaseWindow.fromId(id); return isBrowserWindow(win) ? win as any as BWT : null; }; BrowserWindow.getAllWindows = () => { return BaseWindow.getAllWindows().filter(isBrowserWindow) as any[] as BWT[]; }; BrowserWindow.getFocusedWindow = () => { for (const window of BrowserWindow.getAllWindows()) { if (!window.isDestroyed() && window.webContents && !window.webContents.isDestroyed()) { if (window.isFocused() || window.webContents.isDevToolsFocused()) return window; } } return null; }; BrowserWindow.fromWebContents = (webContents: WebContents) => { return webContents.getOwnerBrowserWindow(); }; BrowserWindow.fromBrowserView = (browserView: BrowserView) => { return BrowserWindow.fromWebContents(browserView.webContents); }; BrowserWindow.prototype.setTouchBar = function (touchBar) { (TouchBar as any)._setOnWindow(touchBar, this); }; // Forwarded to webContents: BrowserWindow.prototype.loadURL = function (...args) { return this.webContents.loadURL(...args); }; BrowserWindow.prototype.getURL = function () { return this.webContents.getURL(); }; BrowserWindow.prototype.loadFile = function (...args) { return this.webContents.loadFile(...args); }; BrowserWindow.prototype.reload = function (...args) { return this.webContents.reload(...args); }; BrowserWindow.prototype.send = function (...args) { return this.webContents.send(...args); }; BrowserWindow.prototype.openDevTools = function (...args) { return this.webContents.openDevTools(...args); }; BrowserWindow.prototype.closeDevTools = function () { return this.webContents.closeDevTools(); }; BrowserWindow.prototype.isDevToolsOpened = function () { return this.webContents.isDevToolsOpened(); }; BrowserWindow.prototype.isDevToolsFocused = function () { return this.webContents.isDevToolsFocused(); }; BrowserWindow.prototype.toggleDevTools = function () { return this.webContents.toggleDevTools(); }; BrowserWindow.prototype.inspectElement = function (...args) { return this.webContents.inspectElement(...args); }; BrowserWindow.prototype.inspectSharedWorker = function () { return this.webContents.inspectSharedWorker(); }; BrowserWindow.prototype.inspectServiceWorker = function () { return this.webContents.inspectServiceWorker(); }; BrowserWindow.prototype.showDefinitionForSelection = function () { return this.webContents.showDefinitionForSelection(); }; BrowserWindow.prototype.capturePage = function (...args) { return this.webContents.capturePage(...args); }; BrowserWindow.prototype.getBackgroundThrottling = function () { return this.webContents.getBackgroundThrottling(); }; BrowserWindow.prototype.setBackgroundThrottling = function (allowed: boolean) { return this.webContents.setBackgroundThrottling(allowed); }; module.exports = BrowserWindow;
closed
electron/electron
https://github.com/electron/electron
38,170
[Bug]: Accessing `BrowserWindow.id` throws an error after the window is closed/destroyed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.1.3 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I want to get the `id` of a `BrowserWindow` object, regardless of whether or not it is closed or destroyed. I expect the following to work: ``` win.on('closed', () => { console.log('window closed, id=', win.id); } ``` ### Actual Behavior It throws an error: ``` TypeError: Object has been destroyed at BrowserWindow.<anonymous> (**/main.js:20:60) at BrowserWindow.emit (node:events:513:28) ``` ### Testcase Gist URL https://gist.github.com/d1819a38f1a9327ae56d4098b9d382d1 ### Additional Information _No response_
https://github.com/electron/electron/issues/38170
https://github.com/electron/electron/pull/38241
042663e19058cebc83428a5a354b863d2bb10e31
9bd9d312f8d59d3a80defba4aeb760e2c3e7e10c
2023-05-03T23:06:01Z
c++
2023-05-16T07:29:00Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,180
[Bug]: getNormalBounds() returns actual window bounds for transparent maximized windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior getNormalBounds() should return last bounds before transparent windows is maximized or minimized ### Actual Behavior getNormalBounds() returning current bounds when transparent windows is maximized or minimized ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38180
https://github.com/electron/electron/pull/38218
ad077125618bb3dc93dd2a660bf6c6956204bae5
32d8f84cad9ece93520d6d1764c9b45403284760
2023-05-04T08:31:21Z
c++
2023-05-17T11:11:43Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent() && !IsMinimized()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetBackgroundMaterial(const std::string& material) { #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,180
[Bug]: getNormalBounds() returns actual window bounds for transparent maximized windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior getNormalBounds() should return last bounds before transparent windows is maximized or minimized ### Actual Behavior getNormalBounds() returning current bounds when transparent windows is maximized or minimized ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38180
https://github.com/electron/electron/pull/38218
ad077125618bb3dc93dd2a660bf6c6956204bae5
32d8f84cad9ece93520d6d1764c9b45403284760
2023-05-04T08:31:21Z
c++
2023-05-17T11:11:43Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,180
[Bug]: getNormalBounds() returns actual window bounds for transparent maximized windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior getNormalBounds() should return last bounds before transparent windows is maximized or minimized ### Actual Behavior getNormalBounds() returning current bounds when transparent windows is maximized or minimized ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38180
https://github.com/electron/electron/pull/38218
ad077125618bb3dc93dd2a660bf6c6956204bae5
32d8f84cad9ece93520d6d1764c9b45403284760
2023-05-04T08:31:21Z
c++
2023-05-17T11:11:43Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/memory/raw_ptr.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: raw_ptr<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent() && !IsMinimized()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetBackgroundMaterial(const std::string& material) { #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,180
[Bug]: getNormalBounds() returns actual window bounds for transparent maximized windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior getNormalBounds() should return last bounds before transparent windows is maximized or minimized ### Actual Behavior getNormalBounds() returning current bounds when transparent windows is maximized or minimized ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38180
https://github.com/electron/electron/pull/38218
ad077125618bb3dc93dd2a660bf6c6956204bae5
32d8f84cad9ece93520d6d1764c9b45403284760
2023-05-04T08:31:21Z
c++
2023-05-17T11:11:43Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,381
[Bug]: getCaptureHandle not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Calling `getCaptureHandle` on a video track should return the shared data See: https://developer.chrome.com/docs/web-platform/capture-handle/ ### Actual Behavior Always returns null ### Testcase Gist URL https://gist.github.com/t57ser/919ff9c9fe623b51fde41772bf4c9207 ### Additional Information Steps to reproduce: After starting the shared gist, click on the "open presentation" button This opens a new window with the content that will be shared Afterwards click "capture" The content can be seen (shared) The issue here is that the following text: "Try sharing a tab that exposes information to capturing applications instead." should display shared information by the content
https://github.com/electron/electron/issues/38381
https://github.com/electron/electron/pull/38390
f07b040cb998a6126979cec9d562acbac5a23c4c
16cd486356ec2883b36095da3e147788b71fddd5
2023-05-19T09:10:38Z
c++
2023-05-24T15:17:08Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value::List current_dictionaries = prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).Clone(); // No configured dictionaries, the default will be en-US if (current_dictionaries.empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { devices.video_device = blink::MediaStreamDevice(request.video_type, id, name); } else if (result_dict.Get("video", &rfh)) { devices.video_device = blink::MediaStreamDevice( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8( content::WebContents::FromRenderFrameHost(rfh)->GetTitle())); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, name); } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; devices.audio_device = blink::MediaStreamDevice(request.audio_type, content::WebContentsMediaCaptureId( rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); } else if (result_dict.Get("audio", &id)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, "System audio"); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,381
[Bug]: getCaptureHandle not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Calling `getCaptureHandle` on a video track should return the shared data See: https://developer.chrome.com/docs/web-platform/capture-handle/ ### Actual Behavior Always returns null ### Testcase Gist URL https://gist.github.com/t57ser/919ff9c9fe623b51fde41772bf4c9207 ### Additional Information Steps to reproduce: After starting the shared gist, click on the "open presentation" button This opens a new window with the content that will be shared Afterwards click "capture" The content can be seen (shared) The issue here is that the following text: "Try sharing a tab that exposes information to capturing applications instead." should display shared information by the content
https://github.com/electron/electron/issues/38381
https://github.com/electron/electron/pull/38390
f07b040cb998a6126979cec9d562acbac5a23c4c
16cd486356ec2883b36095da3e147788b71fddd5
2023-05-19T09:10:38Z
c++
2023-05-24T15:17:08Z
spec/api-media-handler-spec.ts
import { expect } from 'chai'; import { BrowserWindow, session, desktopCapturer } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as http from 'http'; import { ifdescribe, ifit, listen } from './lib/spec-helpers'; const features = process._linkedBinding('electron_common_features'); ifdescribe(features.isDesktopCapturerEnabled())('setDisplayMediaRequestHandler', () => { afterEach(closeAllWindows); // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); // FIXME(nornagon): this test fails on our macOS CircleCI runners with the // error message: // [ERROR:video_capture_device_client.cc(659)] error@ OnStart@content/browser/media/capture/desktop_capture_device_mac.cc:98, CGDisplayStreamCreate failed, OS message: Value too large to be stored in data type (84) // This is possibly related to the OS/VM setup that CircleCI uses for macOS. // Our arm64 runners are in @jkleinsc's office, and are real machines, so the // test works there. ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('works when calling getDisplayMedia', async function () { if ((await desktopCapturer.getSources({ types: ['screen'] })).length === 0) { return this.skip(); } const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. const { id, name } = sources[0]; callback({ video: { id, name } // TODO: 'loopback' and 'loopbackWithMute' are currently only supported on Windows. // audio: { id: 'loopback', name: 'System Audio' } }); }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(message); }); it('does not crash when using a bogus ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'bogus', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(message).to.equal('Could not start video source'); }); it('does not crash when providing only audio for a video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing only an audio stream for an audio+video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing a non-loopback audio stream', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame, audio: 'default' as any }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(); }); it('does not crash when providing no streams', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({}); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when using a bogus web-contents-media-stream:// ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'web-contents-media-stream://9999:9999', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); // This is a little surprising... apparently chrome will generate a stream // for this non-existent web contents? expect(ok).to.be.true(); }); it('is not called when calling getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling getDisplayMedia with preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('can supply a screen response to preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; const sources = await desktopCapturer.getSources({ types: ['screen'] }); callback({ video: sources[0] }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('can supply a frame response', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia with desktop capture constraint', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: { mandatory: { chromeMediaSource: 'desktop' } }, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('works when calling getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling legacy getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('can remove a displayMediaRequestHandler', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); ses.setDisplayMediaRequestHandler(null); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(ok).to.be.false(); expect(message).to.equal('Not supported'); }); });
closed
electron/electron
https://github.com/electron/electron
38,381
[Bug]: getCaptureHandle not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Calling `getCaptureHandle` on a video track should return the shared data See: https://developer.chrome.com/docs/web-platform/capture-handle/ ### Actual Behavior Always returns null ### Testcase Gist URL https://gist.github.com/t57ser/919ff9c9fe623b51fde41772bf4c9207 ### Additional Information Steps to reproduce: After starting the shared gist, click on the "open presentation" button This opens a new window with the content that will be shared Afterwards click "capture" The content can be seen (shared) The issue here is that the following text: "Try sharing a tab that exposes information to capturing applications instead." should display shared information by the content
https://github.com/electron/electron/issues/38381
https://github.com/electron/electron/pull/38390
f07b040cb998a6126979cec9d562acbac5a23c4c
16cd486356ec2883b36095da3e147788b71fddd5
2023-05-19T09:10:38Z
c++
2023-05-24T15:17:08Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value::List current_dictionaries = prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).Clone(); // No configured dictionaries, the default will be en-US if (current_dictionaries.empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { devices.video_device = blink::MediaStreamDevice(request.video_type, id, name); } else if (result_dict.Get("video", &rfh)) { devices.video_device = blink::MediaStreamDevice( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8( content::WebContents::FromRenderFrameHost(rfh)->GetTitle())); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, name); } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; devices.audio_device = blink::MediaStreamDevice(request.audio_type, content::WebContentsMediaCaptureId( rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); } else if (result_dict.Get("audio", &id)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, "System audio"); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,381
[Bug]: getCaptureHandle not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Calling `getCaptureHandle` on a video track should return the shared data See: https://developer.chrome.com/docs/web-platform/capture-handle/ ### Actual Behavior Always returns null ### Testcase Gist URL https://gist.github.com/t57ser/919ff9c9fe623b51fde41772bf4c9207 ### Additional Information Steps to reproduce: After starting the shared gist, click on the "open presentation" button This opens a new window with the content that will be shared Afterwards click "capture" The content can be seen (shared) The issue here is that the following text: "Try sharing a tab that exposes information to capturing applications instead." should display shared information by the content
https://github.com/electron/electron/issues/38381
https://github.com/electron/electron/pull/38390
f07b040cb998a6126979cec9d562acbac5a23c4c
16cd486356ec2883b36095da3e147788b71fddd5
2023-05-19T09:10:38Z
c++
2023-05-24T15:17:08Z
spec/api-media-handler-spec.ts
import { expect } from 'chai'; import { BrowserWindow, session, desktopCapturer } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as http from 'http'; import { ifdescribe, ifit, listen } from './lib/spec-helpers'; const features = process._linkedBinding('electron_common_features'); ifdescribe(features.isDesktopCapturerEnabled())('setDisplayMediaRequestHandler', () => { afterEach(closeAllWindows); // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); // FIXME(nornagon): this test fails on our macOS CircleCI runners with the // error message: // [ERROR:video_capture_device_client.cc(659)] error@ OnStart@content/browser/media/capture/desktop_capture_device_mac.cc:98, CGDisplayStreamCreate failed, OS message: Value too large to be stored in data type (84) // This is possibly related to the OS/VM setup that CircleCI uses for macOS. // Our arm64 runners are in @jkleinsc's office, and are real machines, so the // test works there. ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('works when calling getDisplayMedia', async function () { if ((await desktopCapturer.getSources({ types: ['screen'] })).length === 0) { return this.skip(); } const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. const { id, name } = sources[0]; callback({ video: { id, name } // TODO: 'loopback' and 'loopbackWithMute' are currently only supported on Windows. // audio: { id: 'loopback', name: 'System Audio' } }); }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(message); }); it('does not crash when using a bogus ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'bogus', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(message).to.equal('Could not start video source'); }); it('does not crash when providing only audio for a video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing only an audio stream for an audio+video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing a non-loopback audio stream', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame, audio: 'default' as any }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(); }); it('does not crash when providing no streams', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({}); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when using a bogus web-contents-media-stream:// ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'web-contents-media-stream://9999:9999', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); // This is a little surprising... apparently chrome will generate a stream // for this non-existent web contents? expect(ok).to.be.true(); }); it('is not called when calling getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling getDisplayMedia with preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('can supply a screen response to preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; const sources = await desktopCapturer.getSources({ types: ['screen'] }); callback({ video: sources[0] }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('can supply a frame response', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia with desktop capture constraint', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: { mandatory: { chromeMediaSource: 'desktop' } }, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('works when calling getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling legacy getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('can remove a displayMediaRequestHandler', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); ses.setDisplayMediaRequestHandler(null); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(ok).to.be.false(); expect(message).to.equal('Not supported'); }); });
closed
electron/electron
https://github.com/electron/electron
38,385
[Bug]: Windows look inactive when they're focused on Windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.0.0-beta.3 ### Expected Behavior A basic window with a titlebar should look visually different when in focus (brighter titlebar text and icons, translucent Mica background on Windows 11). Focused: <img width="886" alt="Screenshot 2023-05-21 at 00 54 25" src="https://github.com/electron/electron/assets/7342119/d4449934-8127-412d-bb5f-7000e287e51e"> Unfocused: <img width="928" alt="Screenshot 2023-05-21 at 00 54 34" src="https://github.com/electron/electron/assets/7342119/ec514c73-41a2-407f-afbb-b76f9826300f"> ### Actual Behavior As of the last few betas, windows appear inactive even when they have mouse/keyboard focus. ### Additional Information This bug has implications for the new background material support; the materials will always appear opaque because they only take on styling from the background when the window is focused.
https://github.com/electron/electron/issues/38385
https://github.com/electron/electron/pull/38468
ddcec84ace5f9f3d4bf705c5bd963abc415160d3
56138d879e57d5d5fce55ecbe3f8d3a8ed08e7f8
2023-05-21T04:58:40Z
c++
2023-05-28T22:39:13Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/win/dark_mode.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { const bool dark_mode_supported = win::IsDarkModeSupported(); if (dark_mode_supported && message == WM_NCCREATE) { win::SetDarkModeForWindow(GetAcceleratedWidget()); ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); } else if (dark_mode_supported && message == WM_DESTROY) { ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); } return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by default extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::HandleMouseEventForCaption( UINT message) const { // Windows does not seem to generate WM_NCPOINTERDOWN/UP touch events for // caption buttons with WCO. This results in a no-op for // HWNDMessageHandler::HandlePointerEventTypeTouchOrNonClient and // WM_SYSCOMMAND is not generated for the touch action. However, Windows will // also generate a mouse event for every touch action and this gets handled in // HWNDMessageHandler::HandleMouseEventInternal. // With https://chromium-review.googlesource.com/c/chromium/src/+/1048877/ // Chromium lets the OS handle caption buttons for FrameMode::SYSTEM_DRAWN but // again this does not generate the SC_MINIMIZE, SC_MAXIMIZE, SC_RESTORE // commands when Non-client mouse events are generated for HTCLOSE, // HTMINBUTTON, HTMAXBUTTON. To workaround this issue, wit this delegate we // let chromium handle the mouse events via // HWNDMessageHandler::HandleMouseInputForCaption instead of the OS and this // will generate the necessary system commands to perform caption button // actions due to the DefWindowProc call. // https://source.chromium.org/chromium/chromium/src/+/main:ui/views/win/hwnd_message_handler.cc;l=3611 return native_window_view_->IsWindowControlsOverlayEnabled(); } void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { win::SetDarkModeForWindow(GetAcceleratedWidget()); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,385
[Bug]: Windows look inactive when they're focused on Windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.0.0-beta.3 ### Expected Behavior A basic window with a titlebar should look visually different when in focus (brighter titlebar text and icons, translucent Mica background on Windows 11). Focused: <img width="886" alt="Screenshot 2023-05-21 at 00 54 25" src="https://github.com/electron/electron/assets/7342119/d4449934-8127-412d-bb5f-7000e287e51e"> Unfocused: <img width="928" alt="Screenshot 2023-05-21 at 00 54 34" src="https://github.com/electron/electron/assets/7342119/ec514c73-41a2-407f-afbb-b76f9826300f"> ### Actual Behavior As of the last few betas, windows appear inactive even when they have mouse/keyboard focus. ### Additional Information This bug has implications for the new background material support; the materials will always appear opaque because they only take on styling from the background when the window is focused.
https://github.com/electron/electron/issues/38385
https://github.com/electron/electron/pull/38468
ddcec84ace5f9f3d4bf705c5bd963abc415160d3
56138d879e57d5d5fce55ecbe3f8d3a8ed08e7f8
2023-05-21T04:58:40Z
c++
2023-05-28T22:39:13Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, public ::ui::NativeThemeObserver { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; bool HandleMouseEventForCaption(UINT message) const override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
38,385
[Bug]: Windows look inactive when they're focused on Windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.0.0-beta.3 ### Expected Behavior A basic window with a titlebar should look visually different when in focus (brighter titlebar text and icons, translucent Mica background on Windows 11). Focused: <img width="886" alt="Screenshot 2023-05-21 at 00 54 25" src="https://github.com/electron/electron/assets/7342119/d4449934-8127-412d-bb5f-7000e287e51e"> Unfocused: <img width="928" alt="Screenshot 2023-05-21 at 00 54 34" src="https://github.com/electron/electron/assets/7342119/ec514c73-41a2-407f-afbb-b76f9826300f"> ### Actual Behavior As of the last few betas, windows appear inactive even when they have mouse/keyboard focus. ### Additional Information This bug has implications for the new background material support; the materials will always appear opaque because they only take on styling from the background when the window is focused.
https://github.com/electron/electron/issues/38385
https://github.com/electron/electron/pull/38468
ddcec84ace5f9f3d4bf705c5bd963abc415160d3
56138d879e57d5d5fce55ecbe3f8d3a8ed08e7f8
2023-05-21T04:58:40Z
c++
2023-05-28T22:39:13Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/win/dark_mode.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { const bool dark_mode_supported = win::IsDarkModeSupported(); if (dark_mode_supported && message == WM_NCCREATE) { win::SetDarkModeForWindow(GetAcceleratedWidget()); ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); } else if (dark_mode_supported && message == WM_DESTROY) { ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); } return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by default extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::HandleMouseEventForCaption( UINT message) const { // Windows does not seem to generate WM_NCPOINTERDOWN/UP touch events for // caption buttons with WCO. This results in a no-op for // HWNDMessageHandler::HandlePointerEventTypeTouchOrNonClient and // WM_SYSCOMMAND is not generated for the touch action. However, Windows will // also generate a mouse event for every touch action and this gets handled in // HWNDMessageHandler::HandleMouseEventInternal. // With https://chromium-review.googlesource.com/c/chromium/src/+/1048877/ // Chromium lets the OS handle caption buttons for FrameMode::SYSTEM_DRAWN but // again this does not generate the SC_MINIMIZE, SC_MAXIMIZE, SC_RESTORE // commands when Non-client mouse events are generated for HTCLOSE, // HTMINBUTTON, HTMAXBUTTON. To workaround this issue, wit this delegate we // let chromium handle the mouse events via // HWNDMessageHandler::HandleMouseInputForCaption instead of the OS and this // will generate the necessary system commands to perform caption button // actions due to the DefWindowProc call. // https://source.chromium.org/chromium/chromium/src/+/main:ui/views/win/hwnd_message_handler.cc;l=3611 return native_window_view_->IsWindowControlsOverlayEnabled(); } void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { win::SetDarkModeForWindow(GetAcceleratedWidget()); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,385
[Bug]: Windows look inactive when they're focused on Windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0-beta.7 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.0.0-beta.3 ### Expected Behavior A basic window with a titlebar should look visually different when in focus (brighter titlebar text and icons, translucent Mica background on Windows 11). Focused: <img width="886" alt="Screenshot 2023-05-21 at 00 54 25" src="https://github.com/electron/electron/assets/7342119/d4449934-8127-412d-bb5f-7000e287e51e"> Unfocused: <img width="928" alt="Screenshot 2023-05-21 at 00 54 34" src="https://github.com/electron/electron/assets/7342119/ec514c73-41a2-407f-afbb-b76f9826300f"> ### Actual Behavior As of the last few betas, windows appear inactive even when they have mouse/keyboard focus. ### Additional Information This bug has implications for the new background material support; the materials will always appear opaque because they only take on styling from the background when the window is focused.
https://github.com/electron/electron/issues/38385
https://github.com/electron/electron/pull/38468
ddcec84ace5f9f3d4bf705c5bd963abc415160d3
56138d879e57d5d5fce55ecbe3f8d3a8ed08e7f8
2023-05-21T04:58:40Z
c++
2023-05-28T22:39:13Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, public ::ui::NativeThemeObserver { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; bool HandleMouseEventForCaption(UINT message) const override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "base/mac/scoped_nsobject.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_.get(); } ElectronTouchBar* touch_bar() const { return touch_bar_.get(); } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_; base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include <algorithm> #include "base/mac/mac_util.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/native_widget_mac.h" using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle; using FullScreenTransitionState = electron::NativeWindow::FullScreenTransitionState; @implementation ElectronNSWindowDelegate - (id)initWithShell:(electron::NativeWindowMac*)shell { // The views library assumes the window delegate must be an instance of // ViewsNSWindowDelegate, since we don't have a way to override the creation // of NSWindowDelegate, we have to dynamically replace the window delegate // on the fly. // TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating // window delegate. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); if ((self = [super initWithBridgedNativeWidget:bridged_view])) { shell_ = shell; is_zooming_ = false; level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level]; } return self; } #pragma mark - NSWindowDelegate - (void)windowDidChangeOcclusionState:(NSNotification*)notification { // notification.object is the window that changed its state. // It's safe to use self.window instead if you don't assign one delegate to // many windows NSWindow* window = notification.object; // check occlusion binary flag if (window.occlusionState & NSWindowOcclusionStateVisible) { // The app is visible shell_->NotifyWindowShow(); } else { // The app is not visible shell_->NotifyWindowHide(); } } // Called when the user clicks the zoom button or selects it from the Window // menu to determine the "standard size" of the window. - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)frame { if (!shell_->zoom_to_page_width()) { if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } // If the shift key is down, maximize. if ([[NSApp currentEvent] modifierFlags] & NSEventModifierFlagShift) return frame; // Get preferred width from observers. Usually the page width. int preferred_width = 0; shell_->NotifyWindowRequestPreferredWidth(&preferred_width); // Never shrink from the current size on zoom. NSRect window_frame = [window frame]; CGFloat zoomed_width = std::max(static_cast<CGFloat>(preferred_width), NSWidth(window_frame)); // |frame| determines our maximum extents. We need to set the origin of the // frame -- and only move it left if necessary. if (window_frame.origin.x + zoomed_width > NSMaxX(frame)) frame.origin.x = NSMaxX(frame) - zoomed_width; else frame.origin.x = window_frame.origin.x; // Set the width. Don't touch y or height. frame.size.width = zoomed_width; if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } - (void)windowDidBecomeMain:(NSNotification*)notification { shell_->NotifyWindowFocus(); shell_->RedrawTrafficLights(); } - (void)windowDidResignMain:(NSNotification*)notification { shell_->NotifyWindowBlur(); shell_->RedrawTrafficLights(); } - (void)windowDidBecomeKey:(NSNotification*)notification { shell_->NotifyWindowIsKeyChanged(true); shell_->RedrawTrafficLights(); } - (void)windowDidResignKey:(NSNotification*)notification { // If our app is still active and we're still the key window, ignore this // message, since it just means that a menu extra (on the "system status bar") // was activated; we'll get another |-windowDidResignKey| if we ever really // lose key window status. if ([NSApp isActive] && ([NSApp keyWindow] == [notification object])) return; shell_->NotifyWindowIsKeyChanged(false); shell_->RedrawTrafficLights(); } - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize { NSSize newSize = frameSize; double aspectRatio = shell_->GetAspectRatio(); NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double titleBarHeight = windowSize.height() - contentSize.height(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = titleBarHeight + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); // Clamp to minimum width/height while ensuring aspect ratio remains. NSSize minSize = [window minSize]; NSSize zeroSize = shell_->has_frame() ? NSMakeSize(0, titleBarHeight) : NSZeroSize; if (!NSEqualSizes(minSize, zeroSize)) { double minWidthForAspectRatio = (minSize.height - titleBarHeight) * aspectRatio; bool atMinHeight = minSize.height > zeroSize.height && newSize.height <= minSize.height; newSize.width = atMinHeight ? minWidthForAspectRatio : std::max(newSize.width, minSize.width); double minHeightForAspectRatio = minSize.width / aspectRatio; bool atMinWidth = minSize.width > zeroSize.width && newSize.width <= minSize.width; newSize.height = atMinWidth ? minHeightForAspectRatio : std::max(newSize.height, minSize.height); } // Clamp to maximum width/height while ensuring aspect ratio remains. NSSize maxSize = [window maxSize]; if (!NSEqualSizes(maxSize, NSMakeSize(FLT_MAX, FLT_MAX))) { double maxWidthForAspectRatio = maxSize.height * aspectRatio; bool atMaxHeight = maxSize.height < FLT_MAX && newSize.height >= maxSize.height; newSize.width = atMaxHeight ? maxWidthForAspectRatio : std::min(newSize.width, maxSize.width); double maxHeightForAspectRatio = maxSize.width / aspectRatio; bool atMaxWidth = maxSize.width < FLT_MAX && newSize.width >= maxSize.width; newSize.height = atMaxWidth ? maxHeightForAspectRatio : std::min(newSize.height, maxSize.height); } } if (!resizingHorizontally_) { const auto widthDelta = frameSize.width - [window frame].size.width; const auto heightDelta = frameSize.height - [window frame].size.height; resizingHorizontally_ = std::abs(widthDelta) > std::abs(heightDelta); } { bool prevent_default = false; NSRect new_bounds = NSMakeRect(sender.frame.origin.x, sender.frame.origin.y, newSize.width, newSize.height); shell_->NotifyWindowWillResize(gfx::ScreenRectFromNSRect(new_bounds), *resizingHorizontally_ ? gfx::ResizeEdge::kRight : gfx::ResizeEdge::kBottom, &prevent_default); if (prevent_default) { return sender.frame.size; } } return newSize; } - (void)windowDidResize:(NSNotification*)notification { [super windowDidResize:notification]; shell_->NotifyWindowResize(); shell_->RedrawTrafficLights(); } - (void)windowWillMove:(NSNotification*)notification { NSWindow* window = [notification object]; NSSize size = [[window contentView] frame].size; NSRect new_bounds = NSMakeRect(window.frame.origin.x, window.frame.origin.y, size.width, size.height); bool prevent_default = false; // prevent_default has no effect shell_->NotifyWindowWillMove(gfx::ScreenRectFromNSRect(new_bounds), &prevent_default); } - (void)windowDidMove:(NSNotification*)notification { [super windowDidMove:notification]; // TODO(zcbenz): Remove the alias after figuring out a proper // way to dispatch move. shell_->NotifyWindowMove(); shell_->NotifyWindowMoved(); } - (void)windowWillMiniaturize:(NSNotification*)notification { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); // store the current status window level to be restored in // windowDidDeminiaturize level_ = [window level]; shell_->SetWindowLevel(NSNormalWindowLevel); shell_->UpdateWindowOriginalFrame(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->SetWindowLevel(level_); shell_->NotifyWindowRestore(); } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { is_zooming_ = true; return YES; } - (void)windowDidEndLiveResize:(NSNotification*)notification { resizingHorizontally_.reset(); shell_->NotifyWindowResized(); if (is_zooming_) { if (shell_->IsMaximized()) shell_->NotifyWindowMaximize(); else shell_->NotifyWindowUnmaximize(); is_zooming_ = false; } } - (void)windowWillEnterFullScreen:(NSNotification*)notification { // Store resizable mask so it can be restored after exiting fullscreen. is_resizable_ = shell_->HasStyleMask(NSWindowStyleMaskResizable); shell_->set_fullscreen_transition_state(FullScreenTransitionState::kEntering); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kExiting); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->SetResizable(is_resizable_); shell_->NotifyWindowLeaveFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillClose:(NSNotification*)notification { shell_->Cleanup(); shell_->NotifyWindowClosed(); // Something called -[NSWindow close] on a sheet rather than calling // -[NSWindow endSheet:] on its parent. If the modal session is not ended // then the parent will never be able to show another sheet. But calling // -endSheet: here will block the thread with an animation, so post a task. if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); NSWindow* sheetParent = [window sheetParent]; base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(base::RetainBlock(^{ [sheetParent endSheet:window]; }))); } // Clears the delegate when window is going to be closed, since EL Capitan it // is possible that the methods of delegate would get called after the window // has been closed. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell_->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); bridged_view->OnWindowWillClose(); } - (BOOL)windowShouldClose:(id)window { shell_->NotifyWindowCloseButtonClicked(); return NO; } - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { NSView* view = window.contentView; rect.origin.x = shell_->GetSheetOffsetX(); rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY(); return rect; } - (void)windowWillBeginSheet:(NSNotification*)notification { shell_->NotifyWindowSheetBegin(); } - (void)windowDidEndSheet:(NSNotification*)notification { shell_->NotifyWindowSheetEnd(); } - (IBAction)newWindowForTab:(id)sender { shell_->NotifyNewWindowForTab(); electron::Browser::Get()->NewWindowForTab(); } #pragma mark - NSTouchBarDelegate - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { if (touchBar && shell_->touch_bar()) return [shell_->touch_bar() makeItemForIdentifier:identifier]; else return nil; } #pragma mark - QLPreviewPanelDataSource - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel { return 1; } - (id<QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index { return shell_->preview_item(); } @end
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/common/api/api.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Minimum and maximum size, stored as content size. extensions::SizeConstraints size_constraints_; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "base/mac/scoped_nsobject.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_.get(); } ElectronTouchBar* touch_bar() const { return touch_bar_.get(); } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_; base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include <algorithm> #include "base/mac/mac_util.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/native_widget_mac.h" using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle; using FullScreenTransitionState = electron::NativeWindow::FullScreenTransitionState; @implementation ElectronNSWindowDelegate - (id)initWithShell:(electron::NativeWindowMac*)shell { // The views library assumes the window delegate must be an instance of // ViewsNSWindowDelegate, since we don't have a way to override the creation // of NSWindowDelegate, we have to dynamically replace the window delegate // on the fly. // TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating // window delegate. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); if ((self = [super initWithBridgedNativeWidget:bridged_view])) { shell_ = shell; is_zooming_ = false; level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level]; } return self; } #pragma mark - NSWindowDelegate - (void)windowDidChangeOcclusionState:(NSNotification*)notification { // notification.object is the window that changed its state. // It's safe to use self.window instead if you don't assign one delegate to // many windows NSWindow* window = notification.object; // check occlusion binary flag if (window.occlusionState & NSWindowOcclusionStateVisible) { // The app is visible shell_->NotifyWindowShow(); } else { // The app is not visible shell_->NotifyWindowHide(); } } // Called when the user clicks the zoom button or selects it from the Window // menu to determine the "standard size" of the window. - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)frame { if (!shell_->zoom_to_page_width()) { if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } // If the shift key is down, maximize. if ([[NSApp currentEvent] modifierFlags] & NSEventModifierFlagShift) return frame; // Get preferred width from observers. Usually the page width. int preferred_width = 0; shell_->NotifyWindowRequestPreferredWidth(&preferred_width); // Never shrink from the current size on zoom. NSRect window_frame = [window frame]; CGFloat zoomed_width = std::max(static_cast<CGFloat>(preferred_width), NSWidth(window_frame)); // |frame| determines our maximum extents. We need to set the origin of the // frame -- and only move it left if necessary. if (window_frame.origin.x + zoomed_width > NSMaxX(frame)) frame.origin.x = NSMaxX(frame) - zoomed_width; else frame.origin.x = window_frame.origin.x; // Set the width. Don't touch y or height. frame.size.width = zoomed_width; if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } - (void)windowDidBecomeMain:(NSNotification*)notification { shell_->NotifyWindowFocus(); shell_->RedrawTrafficLights(); } - (void)windowDidResignMain:(NSNotification*)notification { shell_->NotifyWindowBlur(); shell_->RedrawTrafficLights(); } - (void)windowDidBecomeKey:(NSNotification*)notification { shell_->NotifyWindowIsKeyChanged(true); shell_->RedrawTrafficLights(); } - (void)windowDidResignKey:(NSNotification*)notification { // If our app is still active and we're still the key window, ignore this // message, since it just means that a menu extra (on the "system status bar") // was activated; we'll get another |-windowDidResignKey| if we ever really // lose key window status. if ([NSApp isActive] && ([NSApp keyWindow] == [notification object])) return; shell_->NotifyWindowIsKeyChanged(false); shell_->RedrawTrafficLights(); } - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize { NSSize newSize = frameSize; double aspectRatio = shell_->GetAspectRatio(); NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double titleBarHeight = windowSize.height() - contentSize.height(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = titleBarHeight + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); // Clamp to minimum width/height while ensuring aspect ratio remains. NSSize minSize = [window minSize]; NSSize zeroSize = shell_->has_frame() ? NSMakeSize(0, titleBarHeight) : NSZeroSize; if (!NSEqualSizes(minSize, zeroSize)) { double minWidthForAspectRatio = (minSize.height - titleBarHeight) * aspectRatio; bool atMinHeight = minSize.height > zeroSize.height && newSize.height <= minSize.height; newSize.width = atMinHeight ? minWidthForAspectRatio : std::max(newSize.width, minSize.width); double minHeightForAspectRatio = minSize.width / aspectRatio; bool atMinWidth = minSize.width > zeroSize.width && newSize.width <= minSize.width; newSize.height = atMinWidth ? minHeightForAspectRatio : std::max(newSize.height, minSize.height); } // Clamp to maximum width/height while ensuring aspect ratio remains. NSSize maxSize = [window maxSize]; if (!NSEqualSizes(maxSize, NSMakeSize(FLT_MAX, FLT_MAX))) { double maxWidthForAspectRatio = maxSize.height * aspectRatio; bool atMaxHeight = maxSize.height < FLT_MAX && newSize.height >= maxSize.height; newSize.width = atMaxHeight ? maxWidthForAspectRatio : std::min(newSize.width, maxSize.width); double maxHeightForAspectRatio = maxSize.width / aspectRatio; bool atMaxWidth = maxSize.width < FLT_MAX && newSize.width >= maxSize.width; newSize.height = atMaxWidth ? maxHeightForAspectRatio : std::min(newSize.height, maxSize.height); } } if (!resizingHorizontally_) { const auto widthDelta = frameSize.width - [window frame].size.width; const auto heightDelta = frameSize.height - [window frame].size.height; resizingHorizontally_ = std::abs(widthDelta) > std::abs(heightDelta); } { bool prevent_default = false; NSRect new_bounds = NSMakeRect(sender.frame.origin.x, sender.frame.origin.y, newSize.width, newSize.height); shell_->NotifyWindowWillResize(gfx::ScreenRectFromNSRect(new_bounds), *resizingHorizontally_ ? gfx::ResizeEdge::kRight : gfx::ResizeEdge::kBottom, &prevent_default); if (prevent_default) { return sender.frame.size; } } return newSize; } - (void)windowDidResize:(NSNotification*)notification { [super windowDidResize:notification]; shell_->NotifyWindowResize(); shell_->RedrawTrafficLights(); } - (void)windowWillMove:(NSNotification*)notification { NSWindow* window = [notification object]; NSSize size = [[window contentView] frame].size; NSRect new_bounds = NSMakeRect(window.frame.origin.x, window.frame.origin.y, size.width, size.height); bool prevent_default = false; // prevent_default has no effect shell_->NotifyWindowWillMove(gfx::ScreenRectFromNSRect(new_bounds), &prevent_default); } - (void)windowDidMove:(NSNotification*)notification { [super windowDidMove:notification]; // TODO(zcbenz): Remove the alias after figuring out a proper // way to dispatch move. shell_->NotifyWindowMove(); shell_->NotifyWindowMoved(); } - (void)windowWillMiniaturize:(NSNotification*)notification { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); // store the current status window level to be restored in // windowDidDeminiaturize level_ = [window level]; shell_->SetWindowLevel(NSNormalWindowLevel); shell_->UpdateWindowOriginalFrame(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->SetWindowLevel(level_); shell_->NotifyWindowRestore(); } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { is_zooming_ = true; return YES; } - (void)windowDidEndLiveResize:(NSNotification*)notification { resizingHorizontally_.reset(); shell_->NotifyWindowResized(); if (is_zooming_) { if (shell_->IsMaximized()) shell_->NotifyWindowMaximize(); else shell_->NotifyWindowUnmaximize(); is_zooming_ = false; } } - (void)windowWillEnterFullScreen:(NSNotification*)notification { // Store resizable mask so it can be restored after exiting fullscreen. is_resizable_ = shell_->HasStyleMask(NSWindowStyleMaskResizable); shell_->set_fullscreen_transition_state(FullScreenTransitionState::kEntering); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kExiting); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->SetResizable(is_resizable_); shell_->NotifyWindowLeaveFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillClose:(NSNotification*)notification { shell_->Cleanup(); shell_->NotifyWindowClosed(); // Something called -[NSWindow close] on a sheet rather than calling // -[NSWindow endSheet:] on its parent. If the modal session is not ended // then the parent will never be able to show another sheet. But calling // -endSheet: here will block the thread with an animation, so post a task. if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); NSWindow* sheetParent = [window sheetParent]; base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(base::RetainBlock(^{ [sheetParent endSheet:window]; }))); } // Clears the delegate when window is going to be closed, since EL Capitan it // is possible that the methods of delegate would get called after the window // has been closed. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell_->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); bridged_view->OnWindowWillClose(); } - (BOOL)windowShouldClose:(id)window { shell_->NotifyWindowCloseButtonClicked(); return NO; } - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { NSView* view = window.contentView; rect.origin.x = shell_->GetSheetOffsetX(); rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY(); return rect; } - (void)windowWillBeginSheet:(NSNotification*)notification { shell_->NotifyWindowSheetBegin(); } - (void)windowDidEndSheet:(NSNotification*)notification { shell_->NotifyWindowSheetEnd(); } - (IBAction)newWindowForTab:(id)sender { shell_->NotifyNewWindowForTab(); electron::Browser::Get()->NewWindowForTab(); } #pragma mark - NSTouchBarDelegate - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { if (touchBar && shell_->touch_bar()) return [shell_->touch_bar() makeItemForIdentifier:identifier]; else return nil; } #pragma mark - QLPreviewPanelDataSource - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel { return 1; } - (id<QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index { return shell_->preview_item(); } @end
closed
electron/electron
https://github.com/electron/electron
38,459
[Bug]: DCHECK when minimizing parent window with non-modal child on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version [`main@ddcec84`](https://github.com/electron/electron/commit/ddcec84ace5f9f3d4bf705c5bd963abc415160d3) ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.3 (22E252) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior A parent window with a non-modal child can be minimized with no errors. ### Actual Behavior There is a DCHECK: <details> ``` [84022:0525/192146.720343:FATAL:native_widget_ns_window_bridge.mm(1688)] Check failed: 0u == CountBridgedWindows([window_ childWindows]) (0 vs. 1) 0 Electron Framework 0x000000011c10ccf8 base::debug::CollectStackTrace(void**, unsigned long) + 28 1 Electron Framework 0x000000011c0fdee8 base::debug::StackTrace::StackTrace() + 24 2 Electron Framework 0x000000011c04a08c logging::LogMessage::~LogMessage() + 156 3 Electron Framework 0x000000011c0360e0 logging::(anonymous namespace)::DCheckLogMessage::~DCheckLogMessage() + 60 4 Electron Framework 0x000000011c035eec logging::CheckError::~CheckError() + 40 5 Electron Framework 0x000000011c035f1c logging::CheckError::~CheckError() + 12 6 Electron Framework 0x000000011db23f58 remote_cocoa::NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() + 796 7 Electron Framework 0x000000011db23c20 remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() + 160 8 Electron Framework 0x0000000117ac4bfc -[ElectronNSWindowDelegate windowDidMiniaturize:] + 48 9 CoreFoundation 0x00000001a5993254 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 10 CoreFoundation 0x00000001a5a2ef30 ___CFXRegistrationPost_block_invoke + 88 11 CoreFoundation 0x00000001a5a2ee78 _CFXRegistrationPost + 440 12 CoreFoundation 0x00000001a5964580 _CFXNotificationPost + 704 13 Foundation 0x00000001a68c19e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 14 AppKit 0x00000001a93a58e8 -[NSWindow(NSWindow_Theme) _finishMinimizeToDock] + 244 15 AppKit 0x00000001a8ceb534 _NSCGSDockMessageReceive + 460 16 HIToolbox 0x00000001af1f76ac DockCallback(unsigned int, unsigned int, void*, void*) + 1528 17 HIServices 0x00000001ab11b3f0 _DCXTransactionComplete + 56 18 HIServices 0x00000001ab11b38c _XTransactionComplete + 60 19 HIServices 0x00000001ab10c52c mshMIGPerform + 204 20 CoreFoundation 0x00000001a599eca0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 21 CoreFoundation 0x00000001a599ebc0 __CFRunLoopDoSource1 + 520 22 CoreFoundation 0x00000001a599d5a0 __CFRunLoopRun + 2240 23 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 24 HIServices 0x00000001ab11b30c waitForTransaction + 196 25 AppKit 0x00000001a939de14 minimizeItems + 120 26 AppKit 0x00000001a93a4fa4 -[NSWindow(NSWindow_Theme) _regularMinimizeToDock] + 60 27 Electron Framework 0x000000011db1de00 -[NativeWidgetMacNSWindow _regularMinimizeToDock] + 96 28 AppKit 0x00000001a93a4fe4 -[NSWindow(NSWindow_Theme) _minimizeToDockBypassingWindowManager] + 36 29 AppKit 0x00000001a952113c __75-[NSWMWindowCoordinator clientWindowManager:windowMiniaturizationResponse:]_block_invoke + 424 30 AppKit 0x00000001a952179c ___NSMainRunLoopPerformBlockInModes_block_invoke + 44 31 CoreFoundation 0x00000001a599e2a8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28 32 CoreFoundation 0x00000001a599e1bc __CFRunLoopDoBlocks + 364 33 CoreFoundation 0x00000001a599d660 __CFRunLoopRun + 2432 34 CoreFoundation 0x00000001a599c58c CFRunLoopRunSpecific + 612 35 HIToolbox 0x00000001af1d1df4 RunCurrentEventLoopInMode + 292 36 HIToolbox 0x00000001af1d1c30 ReceiveNextEventCommon + 648 37 HIToolbox 0x00000001af1d1988 _BlockUntilNextEventMatchingListInModeWithFilter + 76 38 AppKit 0x00000001a8bbbf58 _DPSNextEvent + 636 39 AppKit 0x00000001a8bbb0f4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 40 AppKit 0x00000001a8baf558 -[NSApplication run] + 464 41 Electron Framework 0x000000011c125054 base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 264 42 Electron Framework 0x000000011c1238c4 base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 144 43 Electron Framework 0x000000011c0bd5a8 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 472 44 Electron Framework 0x000000011c077344 base::RunLoop::Run(base::Location const&) + 396 45 Electron Framework 0x000000011ae5e304 content::BrowserMainLoop::RunMainMessageLoop() + 140 46 Electron Framework 0x000000011ae60038 content::BrowserMainRunnerImpl::Run() + 44 47 Electron Framework 0x000000011ae5b7f4 content::BrowserMain(content::MainFunctionParams) + 160 48 Electron Framework 0x0000000117c10388 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 280 49 Electron Framework 0x0000000117c118a4 content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 600 50 Electron Framework 0x0000000117c114b8 content::ContentMainRunnerImpl::Run() + 808 51 Electron Framework 0x0000000117c0f934 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 1296 52 Electron Framework 0x0000000117c0fb98 content::ContentMain(content::ContentMainParams) + 112 53 Electron Framework 0x00000001178cad9c ElectronMain + 128 54 dyld 0x00000001a5567f28 start + 2236 Crash keys: "amfi-status" = "rv=0 status=0x0 allow_everything=0" "platform" = "darwin" "process_type" = "browser" Electron exited with signal SIGTRAP. ``` </details> ### Testcase Gist URL https://gist.github.com/Levyks/217008d0b1335cb54b0d28101daa69ff ### Additional Information _No response_
https://github.com/electron/electron/issues/38459
https://github.com/electron/electron/pull/38460
13f9e2db40df5537c13ee72a92fad13a0c09b730
40e724e5ddd92879a73fd3eb53af2b128947e9d6
2023-05-25T17:22:21Z
c++
2023-05-31T09:57:44Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-frame-navigate', (e) => { e.preventDefault(); resolve(e.url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); describe('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(1000); navigationEvents.forEach(event => once(w.webContents, event).then(() => firedEvents.push(event)) ); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); describe('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (25.0) ### Deprecated: `protocol.{register,intercept}{Buffer,String,Stream,File,Http}Protocol` The `protocol.register*Protocol` and `protocol.intercept*Protocol` methods have been replaced with [`protocol.handle`](api/protocol.md#protocolhandlescheme-handler). The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type. ```js // Deprecated in Electron 25 protocol.registerBufferProtocol('some-protocol', () => { callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') }) }) // Replace with protocol.handle('some-protocol', () => { return new Response( Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream. { headers: { 'content-type': 'text/html' } } ) }) ``` ```js // Deprecated in Electron 25 protocol.registerHttpProtocol('some-protocol', () => { callback({ url: 'https://electronjs.org' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('https://electronjs.org') }) ``` ```js // Deprecated in Electron 25 protocol.registerFileProtocol('some-protocol', () => { callback({ filePath: '/path/to/my/file' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('file:///path/to/my/file') }) ``` ### Deprecated: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Deprecated in Electron 25 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Deprecated: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been deprecated, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Deprecated in Electron 25 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ## Planned Breaking API Changes (24.0) ### API Changed: `nativeImage.createThumbnailFromPath(path, size)` The `maxSize` parameter has been changed to `size` to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than `maxSize`, and macOS would always set the size to `maxSize`. Behavior is now the same across platforms. Updated Behavior: ```js // a 128x128 image. const imagePath = path.join('path', 'to', 'capybara.png') // Scaling up a smaller image. const upSize = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => { console.log(result.getSize()) // { width: 256, height: 256 } }) // Scaling down a larger image. const downSize = { width: 64, height: 64 } nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => { console.log(result.getSize()) // { width: 64, height: 64 } }) ``` Previous Behavior (on Windows): ```js // a 128x128 image const imagePath = path.join('path', 'to', 'capybara.png') const size = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, size).then(result => { console.log(result.getSize()) // { width: 128, height: 128 } }) ``` ## Planned Breaking API Changes (23.0) ### Behavior Changed: Draggable Regions on macOS The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable. Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion). As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23. ### Removed: Windows 7 / 8 / 8.1 support [Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en). Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher. ### Removed: BrowserWindow `scroll-touch-*` events The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow have been removed. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Removed in Electron 23.0 win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)` The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)` The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ## Planned Breaking API Changes (22.0) ### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)` `webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)` `webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: WebContents `new-window` event The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Removed in Electron 22 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow are deprecated. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Deprecated win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ## Planned Breaking API Changes (21.0) ### Behavior Changed: V8 Memory Cage enabled The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with `ArrayBuffer` or `Buffer`. See the [blog post about the V8 memory cage](https://www.electronjs.org/blog/v8-memory-cage) for more details. ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) ``` ## Planned Breaking API Changes (20.0) ### Removed: macOS 10.11 / 10.12 support macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050). Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher. ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame [`WebFrameMain`](api/web-frame-main.md), but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) ### Removed: IA32 Linux binaries This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the [removal of support for IA32 Linux](#removed-ia32-linux-support). ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](./tutorial/using-native-node-modules.md) for more. ### Removed: IA32 Linux support Electron 18 will no longer run on 32-bit Linux systems. See [discontinuing support for 32-bit Linux](https://www.electronjs.org/blog/linux-32bit-support) for more information. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/child.html
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/index.html
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/main.js
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/preload.js
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/renderer.js
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (25.0) ### Deprecated: `protocol.{register,intercept}{Buffer,String,Stream,File,Http}Protocol` The `protocol.register*Protocol` and `protocol.intercept*Protocol` methods have been replaced with [`protocol.handle`](api/protocol.md#protocolhandlescheme-handler). The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type. ```js // Deprecated in Electron 25 protocol.registerBufferProtocol('some-protocol', () => { callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') }) }) // Replace with protocol.handle('some-protocol', () => { return new Response( Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream. { headers: { 'content-type': 'text/html' } } ) }) ``` ```js // Deprecated in Electron 25 protocol.registerHttpProtocol('some-protocol', () => { callback({ url: 'https://electronjs.org' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('https://electronjs.org') }) ``` ```js // Deprecated in Electron 25 protocol.registerFileProtocol('some-protocol', () => { callback({ filePath: '/path/to/my/file' }) }) // Replace with protocol.handle('some-protocol', () => { return net.fetch('file:///path/to/my/file') }) ``` ### Deprecated: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Deprecated in Electron 25 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Deprecated: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been deprecated, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Deprecated in Electron 25 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ## Planned Breaking API Changes (24.0) ### API Changed: `nativeImage.createThumbnailFromPath(path, size)` The `maxSize` parameter has been changed to `size` to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than `maxSize`, and macOS would always set the size to `maxSize`. Behavior is now the same across platforms. Updated Behavior: ```js // a 128x128 image. const imagePath = path.join('path', 'to', 'capybara.png') // Scaling up a smaller image. const upSize = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => { console.log(result.getSize()) // { width: 256, height: 256 } }) // Scaling down a larger image. const downSize = { width: 64, height: 64 } nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => { console.log(result.getSize()) // { width: 64, height: 64 } }) ``` Previous Behavior (on Windows): ```js // a 128x128 image const imagePath = path.join('path', 'to', 'capybara.png') const size = { width: 256, height: 256 } nativeImage.createThumbnailFromPath(imagePath, size).then(result => { console.log(result.getSize()) // { width: 128, height: 128 } }) ``` ## Planned Breaking API Changes (23.0) ### Behavior Changed: Draggable Regions on macOS The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable. Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion). As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23. ### Removed: Windows 7 / 8 / 8.1 support [Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en). Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher. ### Removed: BrowserWindow `scroll-touch-*` events The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow have been removed. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Removed in Electron 23.0 win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)` The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)` The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ## Planned Breaking API Changes (22.0) ### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)` `webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)` `webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: WebContents `new-window` event The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Removed in Electron 22 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow are deprecated. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Deprecated win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ## Planned Breaking API Changes (21.0) ### Behavior Changed: V8 Memory Cage enabled The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with `ArrayBuffer` or `Buffer`. See the [blog post about the V8 memory cage](https://www.electronjs.org/blog/v8-memory-cage) for more details. ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) ``` ## Planned Breaking API Changes (20.0) ### Removed: macOS 10.11 / 10.12 support macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050). Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher. ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame [`WebFrameMain`](api/web-frame-main.md), but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) ### Removed: IA32 Linux binaries This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the [removal of support for IA32 Linux](#removed-ia32-linux-support). ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](./tutorial/using-native-node-modules.md) for more. ### Removed: IA32 Linux support Electron 18 will no longer run on 32-bit Linux systems. See [discontinuing support for 32-bit Linux](https://www.electronjs.org/blog/linux-32bit-support) for more information. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/child.html
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/index.html
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/main.js
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/preload.js
closed
electron/electron
https://github.com/electron/electron
34,678
[Bug]: Please fix the webview docs
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 13.0.0 ### Expected Behavior When I update electron from 13.0.0 to 19.0.5 ,webview's new-window event will not be triggered when I click a new url. I searched a lot of docs and issues to find this answer . I finally found some discussions in #31117。 In docs [https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated](https://www.electronjs.org/docs/latest/api/web-contents#event-new-window-deprecated) Event: 'new-window' has been deprecated, but there is no any notices or declarations in webview docs: [https://www.electronjs.org/docs/latest/api/webview-tag](https://www.electronjs.org/docs/latest/api/webview-tag) , this is so confused me. Please fix the docs. ### Actual Behavior Please fix the webview docs, add some declarations about event: 'new-window' has been deprecated. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34678
https://github.com/electron/electron/pull/36985
b454f8c7c1e928264dbacc29cd77bd2ac76e16aa
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
2022-06-21T10:54:24Z
c++
2023-05-31T14:47:08Z
docs/fiddles/ipc/webview-new-window/renderer.js
closed
electron/electron
https://github.com/electron/electron
38,484
[Bug]: navigator.connection.rtt is always 0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 24.3.1 ### What operating system are you using? Ubuntu ### Operating System Version 20.04.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Executing `navigator.connection.rtt` should return a non-zero value when configured: ``` window.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) ``` ### Actual Behavior when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values. [Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38484
https://github.com/electron/electron/pull/38491
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
57147d1b8d1352e8f49d6086b9957869d0d1e75a
2023-05-30T04:30:26Z
c++
2023-05-31T15:06:25Z
shell/browser/browser_process_impl.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/browser_process_impl.h" #include <memory> #include <utility> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/sync/os_crypt.h" #include "components/prefs/in_memory_pref_store.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/overlay_user_pref_store.h" #include "components/prefs/pref_registry.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service_factory.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/common/content_switches.h" #include "electron/fuses.h" #include "extensions/common/constants.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_config_service.h" #include "net/proxy_resolution/proxy_config_with_annotation.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "services/network/public/cpp/network_switches.h" #include "shell/common/electron_paths.h" #include "shell/common/thread_restrictions.h" #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_job_manager.h" #endif BrowserProcessImpl::BrowserProcessImpl() { g_browser_process = this; } BrowserProcessImpl::~BrowserProcessImpl() { g_browser_process = nullptr; } // static void BrowserProcessImpl::ApplyProxyModeFromCommandLine( ValueMapPrefStore* pref_store) { if (!pref_store) return; auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kNoProxyServer)) { pref_store->SetValue(proxy_config::prefs::kProxy, base::Value(ProxyConfigDictionary::CreateDirect()), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line->HasSwitch(switches::kProxyPacUrl)) { std::string pac_script_url = command_line->GetSwitchValueASCII(switches::kProxyPacUrl); pref_store->SetValue(proxy_config::prefs::kProxy, base::Value(ProxyConfigDictionary::CreatePacScript( pac_script_url, false /* pac_mandatory */)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line->HasSwitch(switches::kProxyAutoDetect)) { pref_store->SetValue(proxy_config::prefs::kProxy, base::Value(ProxyConfigDictionary::CreateAutoDetect()), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line->HasSwitch(switches::kProxyServer)) { std::string proxy_server = command_line->GetSwitchValueASCII(switches::kProxyServer); std::string bypass_list = command_line->GetSwitchValueASCII(switches::kProxyBypassList); pref_store->SetValue(proxy_config::prefs::kProxy, base::Value(ProxyConfigDictionary::CreateFixedServers( proxy_server, bypass_list)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } } BuildState* BrowserProcessImpl::GetBuildState() { NOTIMPLEMENTED(); return nullptr; } void BrowserProcessImpl::PostEarlyInitialization() { PrefServiceFactory prefs_factory; auto pref_registry = base::MakeRefCounted<PrefRegistrySimple>(); PrefProxyConfigTrackerImpl::RegisterPrefs(pref_registry.get()); #if BUILDFLAG(IS_WIN) OSCrypt::RegisterLocalPrefs(pref_registry.get()); #endif auto pref_store = base::MakeRefCounted<ValueMapPrefStore>(); ApplyProxyModeFromCommandLine(pref_store.get()); prefs_factory.set_command_line_prefs(std::move(pref_store)); // Only use a persistent prefs store when cookie encryption is enabled as that // is the only key that needs it base::FilePath prefs_path; CHECK(base::PathService::Get(electron::DIR_SESSION_DATA, &prefs_path)); prefs_path = prefs_path.Append(FILE_PATH_LITERAL("Local State")); electron::ScopedAllowBlockingForElectron allow_blocking; scoped_refptr<JsonPrefStore> user_pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); user_pref_store->ReadPrefs(); prefs_factory.set_user_prefs(user_pref_store); local_state_ = prefs_factory.Create(std::move(pref_registry)); } void BrowserProcessImpl::PreCreateThreads() { // chrome-extension:// URLs are safe to request anywhere, but may only // commit (including in iframes) in extension processes. content::ChildProcessSecurityPolicy::GetInstance() ->RegisterWebSafeIsolatedScheme(extensions::kExtensionScheme, true); // Must be created before the IOThread. // Once IOThread class is no longer needed, // this can be created on first use. if (!SystemNetworkContextManager::GetInstance()) SystemNetworkContextManager::CreateInstance(local_state_.get()); } void BrowserProcessImpl::PostMainMessageLoopRun() { if (local_state_) local_state_->CommitPendingWrite(); // This expects to be destroyed before the task scheduler is torn down. SystemNetworkContextManager::DeleteInstance(); } bool BrowserProcessImpl::IsShuttingDown() { return false; } metrics_services_manager::MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() { return nullptr; } metrics::MetricsService* BrowserProcessImpl::metrics_service() { return nullptr; } ProfileManager* BrowserProcessImpl::profile_manager() { return nullptr; } PrefService* BrowserProcessImpl::local_state() { DCHECK(local_state_.get()); return local_state_.get(); } scoped_refptr<network::SharedURLLoaderFactory> BrowserProcessImpl::shared_url_loader_factory() { return system_network_context_manager()->GetSharedURLLoaderFactory(); } variations::VariationsService* BrowserProcessImpl::variations_service() { return nullptr; } BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() { return nullptr; } extensions::EventRouterForwarder* BrowserProcessImpl::extension_event_router_forwarder() { return nullptr; } NotificationUIManager* BrowserProcessImpl::notification_ui_manager() { return nullptr; } NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() { return nullptr; } SystemNetworkContextManager* BrowserProcessImpl::system_network_context_manager() { DCHECK(SystemNetworkContextManager::GetInstance()); return SystemNetworkContextManager::GetInstance(); } network::NetworkQualityTracker* BrowserProcessImpl::network_quality_tracker() { return nullptr; } embedder_support::OriginTrialsSettingsStorage* BrowserProcessImpl::GetOriginTrialsSettingsStorage() { return &origin_trials_settings_storage_; } policy::ChromeBrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() { return nullptr; } policy::PolicyService* BrowserProcessImpl::policy_service() { return nullptr; } IconManager* BrowserProcessImpl::icon_manager() { return nullptr; } GpuModeManager* BrowserProcessImpl::gpu_mode_manager() { return nullptr; } printing::PrintPreviewDialogController* BrowserProcessImpl::print_preview_dialog_controller() { return nullptr; } printing::BackgroundPrintingManager* BrowserProcessImpl::background_printing_manager() { return nullptr; } IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() { return nullptr; } DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() { return nullptr; } DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() { return nullptr; } BackgroundModeManager* BrowserProcessImpl::background_mode_manager() { return nullptr; } StatusTray* BrowserProcessImpl::status_tray() { return nullptr; } safe_browsing::SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() { return nullptr; } subresource_filter::RulesetService* BrowserProcessImpl::subresource_filter_ruleset_service() { return nullptr; } component_updater::ComponentUpdateService* BrowserProcessImpl::component_updater() { return nullptr; } MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() { return nullptr; } WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() { return nullptr; } network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() { return nullptr; } gcm::GCMDriver* BrowserProcessImpl::gcm_driver() { return nullptr; } resource_coordinator::ResourceCoordinatorParts* BrowserProcessImpl::resource_coordinator_parts() { return nullptr; } resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() { return nullptr; } SerialPolicyAllowedPorts* BrowserProcessImpl::serial_policy_allowed_ports() { return nullptr; } HidPolicyAllowedDevices* BrowserProcessImpl::hid_policy_allowed_devices() { return nullptr; } HidSystemTrayIcon* BrowserProcessImpl::hid_system_tray_icon() { return nullptr; } void BrowserProcessImpl::SetSystemLocale(const std::string& locale) { system_locale_ = locale; } const std::string& BrowserProcessImpl::GetSystemLocale() const { return system_locale_; } void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) { locale_ = locale; } const std::string& BrowserProcessImpl::GetApplicationLocale() { return locale_; } printing::PrintJobManager* BrowserProcessImpl::print_job_manager() { #if BUILDFLAG(ENABLE_PRINTING) if (!print_job_manager_) print_job_manager_ = std::make_unique<printing::PrintJobManager>(); return print_job_manager_.get(); #else return nullptr; #endif } StartupData* BrowserProcessImpl::startup_data() { return nullptr; } device::GeolocationManager* BrowserProcessImpl::geolocation_manager() { return geolocation_manager_.get(); } void BrowserProcessImpl::SetGeolocationManager( std::unique_ptr<device::GeolocationManager> geolocation_manager) { geolocation_manager_ = std::move(geolocation_manager); }