mirror of
https://github.com/electron/electron.git
synced 2026-10-28 11:44:46 +08:00
feat: add save/restore window state API (#51510)
* feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: support for multimonitor tests (#47911) * test: support for multimonitor tests * fix: update yarn.lock file * test: support any resolution for new displays * test: support display positioning * docs: multi-monitor tests * test: remove dummy test * feat: enforce unique window names across BaseWindow and BrowserWindow (#47764) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: enforce unique window names across BaseWindow and BrowserWindow * docs: update docs for name property * fix: linter issue with symbol --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: clear and restore window state (#47781) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: restore window state * feat: flush display modes on show * refactor: move utility functions to common area * feat: clear window state * fix: wait for the prefs to update * test: clearWindowState extra test * test: refine clear window state tests * test: single monitor restore window tests chore: rebase on gsoc-2025 * refactor: refine clearWindowState test * fix: revert default_app back to original * docs: add comment linking AdjustBoundsToBeVisibleOnDisplay to Chromium code * fix: add correct permalink * refactor: ci friendly * fix: disable windowStatePersistence when no display * refactor: use reference instead pointer * fix: skip window state persistence for invalid/fake displays * refactor: better flag placement * test: add test to verify window state is not saved when no display * fix: restore display mode inside show() * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: clear sharedUserPath before and test * refactor: hasInvalidDisplay function * debug: add display info logging for CI * fix: do not save/restore when window is 0x0 * test: support for multimonitor tests (#47911) * test: support for multimonitor tests * fix: update yarn.lock file * test: support any resolution for new displays * test: support display positioning * docs: multi-monitor tests * test: remove dummy test * feat: enforce unique window names across BaseWindow and BrowserWindow (#47764) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: enforce unique window names across BaseWindow and BrowserWindow * docs: update docs for name property * fix: linter issue with symbol --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: remove invalid display test --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> Co-authored-by: Keeley Hammond <vertedinde@electronjs.org> * test: multi monitor tests for save/restore window state (#48048) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: restore window state * feat: flush display modes on show * refactor: move utility functions to common area * feat: clear window state * fix: wait for the prefs to update * test: clearWindowState extra test * test: refine clear window state tests * test: single monitor restore window tests chore: rebase on gsoc-2025 * refactor: refine clearWindowState test * fix: revert default_app back to original * docs: add comment linking AdjustBoundsToBeVisibleOnDisplay to Chromium code * fix: add correct permalink * refactor: ci friendly * fix: disable windowStatePersistence when no display * refactor: use reference instead pointer * fix: skip window state persistence for invalid/fake displays * refactor: better flag placement * test: add test to verify window state is not saved when no display * fix: restore display mode inside show() * feat: support for multimonitor tests * fix: update yarn.lock file * feat: support any resolution for new displays * feat: support display positioning * docs: multi-monitor tests * test: remove dummy test * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: clear sharedUserPath before and test * refactor: hasInvalidDisplay function * debug: add display info logging for CI * fix: do not save/restore when window is 0x0 * test: support for multimonitor tests (#47911) * test: support for multimonitor tests * fix: update yarn.lock file * test: support any resolution for new displays * test: support display positioning * docs: multi-monitor tests * test: remove dummy test * fix: native-addon forceCleanup * docs: add forceCleanup description * test: add two basic multi-monitor tests * fix: find the closest display for non-overlapping saved bounds * test: windowStatePersistence multi-monitor tests * docs: add note on display APIs in CI * fix: remove duplicate destroy registration * feat: enforce unique window names across BaseWindow and BrowserWindow (#47764) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: enforce unique window names across BaseWindow and BrowserWindow * docs: update docs for name property * fix: linter issue with symbol --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * docs: remove inaccurate comment * fix: move expect blocks outside beforeEach * test: exclude macOS-x64 for now * test: remove invalid display test * test: remove invalid display test * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: support for multimonitor tests (#47911) * test: support for multimonitor tests * fix: update yarn.lock file * test: support any resolution for new displays * test: support display positioning * docs: multi-monitor tests * test: remove dummy test * feat: enforce unique window names across BaseWindow and BrowserWindow (#47764) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: enforce unique window names across BaseWindow and BrowserWindow * docs: update docs for name property * fix: linter issue with symbol --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: clear and restore window state (#47781) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: restore window state * feat: flush display modes on show * refactor: move utility functions to common area * feat: clear window state * fix: wait for the prefs to update * test: clearWindowState extra test * test: refine clear window state tests * test: single monitor restore window tests chore: rebase on gsoc-2025 * refactor: refine clearWindowState test * fix: revert default_app back to original * docs: add comment linking AdjustBoundsToBeVisibleOnDisplay to Chromium code * fix: add correct permalink * refactor: ci friendly * fix: disable windowStatePersistence when no display * refactor: use reference instead pointer * fix: skip window state persistence for invalid/fake displays * refactor: better flag placement * test: add test to verify window state is not saved when no display * fix: restore display mode inside show() * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: clear sharedUserPath before and test * refactor: hasInvalidDisplay function * debug: add display info logging for CI * fix: do not save/restore when window is 0x0 * test: support for multimonitor tests (#47911) * test: support for multimonitor tests * fix: update yarn.lock file * test: support any resolution for new displays * test: support display positioning * docs: multi-monitor tests * test: remove dummy test * feat: enforce unique window names across BaseWindow and BrowserWindow (#47764) * feat: save window state (#47425) * feat: save/restore window state * cleanup * remove constructor option * refactor: apply suggestions from code review Co-authored-by: Charles Kerr <charles@charleskerr.com> * refactor: forward declare prefservice * refactor: remove constructor option * refactor: save window state on move/resize instead of moved/resized * feat: resave window state after construction * test: add basic window save tests * test: add work area tests * test: asynchronous batching behavior * docs: add windowStateRestoreOptions to BaseWindowConstructorOptions * chore: move includes to main block * Update spec/api-browser-window-spec.ts Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * docs: update docs/api/structures/base-window-options.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: preserve original bounds during window state save in special modes * feat: save kiosk state in window preferences * chore: remove ts-expect-error * test: check hasCapturableScreen before running tests * test: remove multimonitor tests * test: add missing hasCapturableScreen checks before tests * docs: add blurb on saving mechanism * feat: add debounce window of 200ms to saveWindowState * docs: remove blurb until finalized * style: convert constants from snake_case to camelCase * refactor: initialize prefs_ only if window state is configured to be saved/restored * refactor: rename window states key * refactor: store in application-level Local State instead of browser context * refactor: switch to more accurate function names * fix: add dcheck for browser_process * fix: flush window state to avoid race condition * refactor: change stateId to name * refactor: change windowStateRestoreOptions to windowStatePersistence * Update docs/api/structures/base-window-options.md Co-authored-by: David Sanders <dsanders11@ucsbalum.com> * fix: add warning when window state persistence enabled without window name * docs: lowercase capital B for consistency --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * feat: enforce unique window names across BaseWindow and BrowserWindow * docs: update docs for name property * fix: linter issue with symbol --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> * test: remove invalid display test --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> Co-authored-by: Keeley Hammond <vertedinde@electronjs.org> --------- Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> Co-authored-by: Keeley Hammond <vertedinde@electronjs.org> * feat: add 'restored-persisted-state' event to BaseWindow (#50516) * docs: add note on display APIs in CI * docs: remove inaccurate comment * test: set show to true * docs: restored-window-state event * feat: add 'restored-window-state' event to BaseWindow * test: add tests for 'restored-window-state' event emission * test: move createWindowAndSave * docs: differentiate between name and title * test: add checks for virtual display creation * docs: tutorial for windowStatePersistence * fix: ensure only single display before multi monitor tests * docs: better docs for virtual display addon * docs: better docs for virtual display addon * refactor: rename event restored-window-state to restored-persisted-state * refactor: rename BaseWindow.clearWindowState to clearPersistedState * docs: improve docs for name property and fix typos * build: run yarn install * fix: update base::Value::Dict -> base::DictValue * fix: add install script to virtual-display native addon The virtual-display fixture was missing an "install" script, so node-gyp never compiled it during `yarn install`. This caused "Cannot find module '../build/Release/virtual_display.node'" in CI. Also removed unused dependencies (bindings, @types/jest, node-gyp) to match the pattern of other native addon fixtures. Co-Authored-By: Claude <svc-devxp-claude@slack-corp.com> --------- Co-authored-by: Nilay Arya <nilay2014@gmail.com> Co-authored-by: Claude <svc-devxp-claude@slack-corp.com> * chore: fixup yarn.lock, lint * chore: fix build errors after rebase onto main Remove stale `#include "shell/browser/native_window_features.h"` (header was deleted in #51160) and add the required `animate` parameter to the `SetBounds` call in `RestoreBounds` (signature changed on main). * fix: rewrite virtual-display addon in Objective-C, removing Swift dependency The CI runner's Xcode 16.4 has a broken Swift toolchain where swift-frontend cannot load lib_CompilerSwiftIDEUtils.dylib. Since the addon only uses CoreGraphics private C/ObjC APIs (CGVirtualDisplay, CGVirtualDisplayDescriptor, etc.), rewrite the implementation entirely in Objective-C to eliminate the Swift compilation step. Co-Authored-By: Claude <svc-devxp-claude@slack-corp.com> * chore: remove nut-js dependent tests * test: fix macos display tests * Update docs/api/base-window.md Co-authored-by: Sam Maddock <samuelmaddock@electronjs.org> * Update docs/tutorial/window-state-persistence.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * Update docs/tutorial/window-state-persistence.md Co-authored-by: Erick Zhao <erick@hotmail.ca> * fix: defer is_being_restored reset and persisted-state-restored to display-mode callback Resetting is_being_restored_ synchronously at the end of RestoreWindowState let the deferred display-mode callback (kiosk/fullscreen/maximize) fire from Show() with the flag already false, so the resize/move events it produced scheduled DebouncedSaveWindowState and persisted transitional bounds over the user's saved bounds. Also rename the BaseWindow event to persisted-state-restored consistently across the C++ emit, tutorial, and spec, and move the 25s busy-loop spec into a spawned Electron fixture so the spec runner main thread isn't blocked. * test: bump main-thread-busy spec timeout to 60s Spawned Electron fixture sleeps 25s plus startup, exceeding mocha's 30s default. * fix: emit persisted-state-restored synchronously, not in deferred callback The previous fix moved NotifyWindowStateRestored() into the deferred display-mode callback to keep it ordered after the kiosk/fullscreen/ maximize change. But that callback only fires from Show() via FlushPendingDisplayMode(), so windows constructed with show: false (and restore_display_mode_ true, which is the default) never emitted the event - including the spec coverage. Restore the synchronous emit and keep the is_being_restored_ deferral, since only the flag reset needs to straddle the deferred resize/move events that schedule DebouncedSaveWindowState. * fix: tie window-state restore guard to display-mode transition lifecycle The is_being_restored_ guard was reset on the deferred display-mode callback invocation rather than the actual restoration lifecycle, which caused three defects: 1. A window created with show:false and destroyed before show() left the guard stuck true, so the close-time FlushWindowState save no-op'd and state changes made while hidden were dropped. 2. showInactive() never flushed the deferred display mode, so a persisted hidden window shown inactive did not re-apply saved fullscreen/ maximize/kiosk and left the guard stuck true. 3. On macOS the guard was reset synchronously after the async SetFullScreen/Maximize/SetKiosk calls, so a flush during the transition persisted transitional bounds over the saved state. Reset the guard from the NotifyWindowEnterFullScreen/NotifyWindowMaximize observers once the transition completes, drain a never-run callback in FlushWindowState, flush the pending display mode from ShowInactive on both backends, and skip saves while a fullscreen transition is in flight. --------- Co-authored-by: Nilay Arya <84241885+nilayarya@users.noreply.github.com> Co-authored-by: Charles Kerr <charles@charleskerr.com> Co-authored-by: David Sanders <dsanders11@ucsbalum.com> Co-authored-by: Erick Zhao <erick@hotmail.ca> Co-authored-by: Nilay Arya <nilay2014@gmail.com> Co-authored-by: Claude <svc-devxp-claude@slack-corp.com> Co-authored-by: George Xu <33054982+georgexu99@users.noreply.github.com> Co-authored-by: Sam Maddock <samuelmaddock@electronjs.org> Co-authored-by: George Xu <george.xu@slack-corp.com>
This commit is contained in:
39 files changed
+3272
-8
No files matched your search
+2
-1
@@ -37,10 +37,11 @@ an issue:
|
||||
* [Represented File for macOS BrowserWindows](tutorial/represented-file.md)
|
||||
* [Native File Drag & Drop](tutorial/native-file-drag-drop.md)
|
||||
* [Navigation History](tutorial/navigation-history.md)
|
||||
* [Window State Persistence](tutorial/window-state-persistence.md)
|
||||
* [Offscreen Rendering](tutorial/offscreen-rendering.md)
|
||||
* [Dark Mode](tutorial/dark-mode.md)
|
||||
* [Web embeds in Electron](tutorial/web-embeds.md)
|
||||
* [Boilerplates and CLIs](tutorial/boilerplates-and-clis.md)
|
||||
* [Boilerplates and CLIs](tutorial/boilerplates-and-clis.md)
|
||||
* [Boilerplate vs CLI](tutorial/boilerplates-and-clis.md#boilerplate-vs-cli)
|
||||
* [Electron Forge](tutorial/boilerplates-and-clis.md#electron-forge)
|
||||
* [electron-builder](tutorial/boilerplates-and-clis.md#electron-builder)
|
||||
|
||||
@@ -377,6 +377,15 @@ Calling `event.preventDefault()` will prevent the menu from being displayed.
|
||||
|
||||
To convert `point` to DIP, use [`screen.screenToDipPoint(point)`](./screen.md#screenscreentodippointpoint-windows-linux).
|
||||
|
||||
#### Event: 'persisted-state-restored'
|
||||
|
||||
Emitted after the persisted window state has been restored.
|
||||
|
||||
Window state includes the window bounds (x, y, height, width) and display mode (maximized, fullscreen, kiosk).
|
||||
|
||||
> [!NOTE]
|
||||
> This event is only emitted when [windowStatePersistence](structures/window-state-persistence.md) is enabled in [BaseWindowConstructorOptions](structures/base-window-options.md) or in [BrowserWindowConstructorOptions](structures/browser-window-options.md).
|
||||
|
||||
### Static Methods
|
||||
|
||||
The `BaseWindow` class has the following static methods:
|
||||
@@ -395,6 +404,14 @@ Returns `BaseWindow | null` - The window that is focused in this application, ot
|
||||
|
||||
Returns `BaseWindow | null` - The window with the given `id`.
|
||||
|
||||
#### `BaseWindow.clearPersistedState(name)`
|
||||
|
||||
* `name` string - The window `name` to clear state for (see [BaseWindowConstructorOptions](structures/base-window-options.md)).
|
||||
|
||||
Clears the saved state for a window with the given name. This removes all persisted window bounds, display mode, and work area information that was previously saved when `windowStatePersistence` was enabled.
|
||||
|
||||
If the window `name` is empty or the window state doesn't exist, the method will log a warning.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
Objects created with `new BaseWindow` have the following properties:
|
||||
|
||||
@@ -42,6 +42,8 @@
|
||||
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`.
|
||||
* `name` string (optional) - A unique identifier for the window, used internally by Electron to enable features such as state persistence. Each window must have a distinct name. It can only be reused after the corresponding window has been destroyed. An error is thrown if the name is already in use. This is not the visible title shown to users on the title bar.
|
||||
* `windowStatePersistence` ([WindowStatePersistence](window-state-persistence.md) | boolean) (optional) - Configures or enables the persistence of window state (position, size, maximized state, etc.) across application restarts. Has no effect if window `name` is not provided. Automatically disabled when there is no available display. _Experimental_
|
||||
* `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
|
||||
@@ -94,7 +96,7 @@
|
||||
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.
|
||||
* `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`.
|
||||
* `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_ _Linux_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
|
||||
* `symbolColor` String (optional) _Windows_ _Linux_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color.
|
||||
* `height` Integer (optional) - The height of the title bar and Window Controls Overlay in pixels. Default is system height.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# WindowStatePersistence Object
|
||||
|
||||
* `bounds` boolean (optional) - Whether to persist window position and size across application restarts. Defaults to `true` if not specified.
|
||||
* `displayMode` boolean (optional) - Whether to persist display modes (fullscreen, kiosk, maximized, etc.) across application restarts. Defaults to `true` if not specified.
|
||||
@@ -0,0 +1,111 @@
|
||||
# Multi-Monitor Testing
|
||||
|
||||
The `virtualDisplay` addon leverages macOS CoreGraphics APIs to create virtual displays, allowing you to write and run multi-monitor tests without the need for physical monitors. Due to macOS CoreGraphics quirks, reading the entire guide once before writing tests is recommended.
|
||||
|
||||
## Methods
|
||||
|
||||
#### `virtualDisplay.create([options])`
|
||||
|
||||
Creates a virtual display and returns a display ID.
|
||||
|
||||
```js @ts-nocheck
|
||||
const virtualDisplay = require('@electron-ci/virtual-display')
|
||||
// Default: 1920×1080 at origin (0, 0)
|
||||
const displayId = virtualDisplay.create()
|
||||
```
|
||||
|
||||
```js @ts-nocheck
|
||||
const virtualDisplay = require('@electron-ci/virtual-display')
|
||||
// Custom options (all parameters optional and have default values)
|
||||
const displayId = virtualDisplay.create({
|
||||
width: 2560, // Display width in pixels
|
||||
height: 1440, // Display height in pixels
|
||||
x: 1920, // X position (top-left corner)
|
||||
y: 0 // Y position (top-left corner)
|
||||
})
|
||||
```
|
||||
|
||||
**Returns:** `number` - Unique display ID used to identify the display. Returns `0` on failure to create display.
|
||||
|
||||
> [!NOTE]
|
||||
> It is recommended to call [`virtualDisplay.forceCleanup()`](#virtualdisplayforcecleanup) before every test to prevent display creation from failing in that test. macOS CoreGraphics maintains an internal display ID allocation pool that can become corrupted when virtual displays are created and destroyed rapidly during testing. Without proper cleanup, subsequent display creation may fail with inconsistent display IDs, resulting in test flakiness.
|
||||
|
||||
#### `virtualDisplay.forceCleanup()`
|
||||
|
||||
Performs a complete cleanup of all virtual displays and resets the macOS CoreGraphics display system.
|
||||
|
||||
```js @ts-nocheck
|
||||
beforeEach(() => {
|
||||
virtualDisplay.forceCleanup()
|
||||
})
|
||||
```
|
||||
|
||||
#### `virtualDisplay.destroy(displayId)`
|
||||
|
||||
Removes the virtual display.
|
||||
|
||||
```js @ts-nocheck
|
||||
virtualDisplay.destroy(displayId)
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Always destroy virtual displays after use to prevent corrupting the macOS CoreGraphics display pool and affecting subsequent tests.
|
||||
|
||||
## Recommended usage pattern
|
||||
|
||||
```js @ts-nocheck
|
||||
describe('multi-monitor tests', () => {
|
||||
const virtualDisplay = require('@electron-ci/virtual-display')
|
||||
beforeEach(() => {
|
||||
virtualDisplay.forceCleanup()
|
||||
})
|
||||
|
||||
it('should handle multiple displays', () => {
|
||||
const display1 = virtualDisplay.create({ width: 1920, height: 1080, x: 0, y: 0 })
|
||||
const display2 = virtualDisplay.create({ width: 2560, height: 1440, x: 1920, y: 0 })
|
||||
// Your test logic here
|
||||
virtualDisplay.destroy(display1)
|
||||
virtualDisplay.destroy(display2)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Display Constraints
|
||||
|
||||
### Size Limits
|
||||
|
||||
Virtual displays are constrained to 720×720 pixels minimum and 8192×8192 pixels maximum. Actual limits may vary depending on your Mac's graphics capabilities, so sizes outside this range (like 9000×6000) may fail on some systems.
|
||||
|
||||
```js @ts-nocheck
|
||||
// Safe sizes for testing
|
||||
virtualDisplay.create({ width: 1920, height: 1080 }) // Full HD
|
||||
virtualDisplay.create({ width: 3840, height: 2160 }) // 4K
|
||||
```
|
||||
|
||||
### Positioning Behavior
|
||||
|
||||
macOS maintains a contiguous desktop space by automatically adjusting display positions if there are any overlaps or gaps. In case of either, the placement of the new origin is as close as possible to the requested location, without overlapping or leaving a gap between displays.
|
||||
|
||||
**Overlap:**
|
||||
|
||||
```js @ts-nocheck
|
||||
// Requested positions
|
||||
const display1 = virtualDisplay.create({ x: 0, y: 0, width: 1920, height: 1080 })
|
||||
const display2 = virtualDisplay.create({ x: 500, y: 0, width: 1920, height: 1080 })
|
||||
|
||||
// macOS automatically repositions display2 to x: 1920 to prevent overlap
|
||||
const actualBounds = screen.getAllDisplays().map(d => d.bounds)
|
||||
// Result: [{ x: 0, y: 0, width: 1920, height: 1080 }, { x: 1920, y: 0, width: 1920, height: 1080 }]
|
||||
```
|
||||
|
||||
**Gap:**
|
||||
|
||||
```js @ts-nocheck
|
||||
// Requested: gap between displays
|
||||
const display1 = virtualDisplay.create({ width: 1920, height: 1080, x: 0, y: 0 })
|
||||
const display2 = virtualDisplay.create({ width: 1920, height: 1080, x: 2000, y: 0 })
|
||||
// macOS snaps display2 to x: 1920 (eliminates 80px gap)
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Always verify actual positions with `screen.getAllDisplays()` after creation, as macOS may adjust coordinates from the set values.
|
||||
@@ -95,3 +95,11 @@ To configure display scaling:
|
||||
|
||||
1. Push the Windows key and search for _Display settings_.
|
||||
2. Under _Scale and layout_, make sure that the device is set to 100%.
|
||||
|
||||
## Multi-Monitor Tests
|
||||
|
||||
Some Electron APIs require testing across multiple displays, such as screen detection, window positioning, and display-related events. For contributors working on these features, the `virtualDisplay` native addon enables you to create and position virtual displays programmatically, making it possible to test multi-monitor scenarios without any physical hardware.
|
||||
|
||||
For detailed information on using virtual displays in your tests, see [Multi-Monitor Testing](multi-monitor-testing.md).
|
||||
|
||||
**Platform support:** macOS only
|
||||
@@ -0,0 +1,102 @@
|
||||
# Window State Persistence
|
||||
|
||||
## Overview
|
||||
|
||||
Window State Persistence allows your Electron application to automatically save and restore a window's position, size, and display modes (such as maximized or fullscreen states) across application restarts.
|
||||
|
||||
This feature is particularly useful for applications where users frequently resize, move, or maximize windows and expect them to remain in the same state when reopening the app.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
To enable Window State Persistence, set `windowStatePersistence: true` in your window constructor options and provide a unique `name` for the window.
|
||||
|
||||
```js
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
function createWindow () {
|
||||
const win = new BrowserWindow({
|
||||
name: 'main-window',
|
||||
width: 800,
|
||||
height: 600,
|
||||
windowStatePersistence: true
|
||||
})
|
||||
|
||||
win.loadFile('index.html')
|
||||
}
|
||||
|
||||
app.whenReady().then(createWindow)
|
||||
```
|
||||
|
||||
With this configuration, Electron will automatically:
|
||||
|
||||
1. Restore the window's position, size, and display mode when created (if a previous state exists)
|
||||
2. Save the window state whenever it changes (position, size, or display mode).
|
||||
3. Emit a `persisted-state-restored` event after successfully restoring state.
|
||||
4. Adapt restored window state to multi-monitor setups and display changes automatically.
|
||||
|
||||
> [!NOTE]
|
||||
> Window State Persistence requires that the window has a unique `name` property set in its constructor options. This name serves as the identifier for storing and retrieving the window's saved state.
|
||||
|
||||
### Selective persistence
|
||||
|
||||
You can control which aspects of the window state are persisted by passing an object with specific options:
|
||||
|
||||
```js
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
function createWindow () {
|
||||
const win = new BrowserWindow({
|
||||
name: 'main-window',
|
||||
width: 800,
|
||||
height: 600,
|
||||
windowStatePersistence: {
|
||||
bounds: true, // Save position and size (default: true)
|
||||
displayMode: false // Don't save maximized/fullscreen/kiosk state (default: true)
|
||||
}
|
||||
})
|
||||
|
||||
win.loadFile('index.html')
|
||||
}
|
||||
|
||||
app.whenReady().then(createWindow)
|
||||
```
|
||||
|
||||
In this example, the window will remember its position and size but will always start in normal mode, even if it was maximized or fullscreened when last closed.
|
||||
|
||||
### Clearing persisted state
|
||||
|
||||
You can programmatically clear the saved state for a specific window using the static `clearPersistedState` method:
|
||||
|
||||
```js
|
||||
const { BrowserWindow } = require('electron')
|
||||
|
||||
// Clear saved state for a specific window
|
||||
BrowserWindow.clearPersistedState('main-window')
|
||||
|
||||
// Now when you create a window with this name,
|
||||
// it will use the default constructor options
|
||||
const win = new BrowserWindow({
|
||||
name: 'main-window',
|
||||
width: 800,
|
||||
height: 600,
|
||||
windowStatePersistence: true
|
||||
})
|
||||
```
|
||||
|
||||
## API reference
|
||||
|
||||
The Window State Persistence APIs are available on both `BaseWindow` and `BrowserWindow` (since `BrowserWindow` extends `BaseWindow`) and work identically.
|
||||
|
||||
For complete API documentation, see:
|
||||
|
||||
- [`windowStatePersistence` in BaseWindowConstructorOptions][base-window-options]
|
||||
- [`WindowStatePersistence` object structure][window-state-persistence-structure]
|
||||
- [`BaseWindow.clearPersistedState()`][clear-persisted-state]
|
||||
- [`persisted-state-restored` event][restored-event]
|
||||
|
||||
[base-window-options]: ../api/structures/base-window-options.md
|
||||
[window-state-persistence-structure]: ../api/structures/window-state-persistence.md
|
||||
[clear-persisted-state]: ../api/base-window.md#basewindowclearpersistedstatename
|
||||
[restored-event]: ../api/base-window.md#event-persisted-state-restored
|
||||
@@ -176,6 +176,7 @@ auto_filenames = {
|
||||
"docs/api/structures/webauthn-account.md",
|
||||
"docs/api/structures/window-open-handler-response.md",
|
||||
"docs/api/structures/window-session-end-event.md",
|
||||
"docs/api/structures/window-state-persistence.md",
|
||||
]
|
||||
|
||||
node_header_sources = [
|
||||
|
||||
@@ -115,6 +115,8 @@ BrowserWindow.getAllWindows = () => {
|
||||
return BaseWindow.getAllWindows().filter(isBrowserWindow) as any[] as BWT[];
|
||||
};
|
||||
|
||||
BrowserWindow.clearPersistedState = BaseWindow.clearPersistedState;
|
||||
|
||||
BrowserWindow.getFocusedWindow = () => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed() && window.webContents && !window.webContents.isDestroyed()) {
|
||||
|
||||
@@ -10,15 +10,20 @@
|
||||
#include <vector>
|
||||
|
||||
#include "base/task/single_thread_task_runner.h"
|
||||
#include "components/prefs/scoped_user_pref_update.h"
|
||||
#include "content/public/common/color_parser.h"
|
||||
#include "electron/buildflags/buildflags.h"
|
||||
#include "gin/dictionary.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/browser_process_impl.h"
|
||||
#include "shell/browser/electron_browser_main_parts.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/browser/native_window.h"
|
||||
#include "shell/browser/window_list.h"
|
||||
#include "shell/common/color_util.h"
|
||||
#include "shell/common/electron_constants.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"
|
||||
@@ -170,7 +175,7 @@ void BaseWindow::OnWindowClosed() {
|
||||
// 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();
|
||||
|
||||
window_->FlushWindowState();
|
||||
Emit("closed");
|
||||
|
||||
parent_window_.Reset();
|
||||
@@ -261,6 +266,7 @@ void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds,
|
||||
}
|
||||
|
||||
void BaseWindow::OnWindowResize() {
|
||||
window_->DebouncedSaveWindowState();
|
||||
Emit("resize");
|
||||
}
|
||||
|
||||
@@ -276,6 +282,7 @@ void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds,
|
||||
}
|
||||
|
||||
void BaseWindow::OnWindowMove() {
|
||||
window_->DebouncedSaveWindowState();
|
||||
Emit("move");
|
||||
}
|
||||
|
||||
@@ -344,6 +351,10 @@ void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) {
|
||||
}
|
||||
}
|
||||
|
||||
void BaseWindow::OnWindowStateRestored() {
|
||||
EmitEventSoon("persisted-state-restored");
|
||||
}
|
||||
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) {
|
||||
if (IsWindowMessageHooked(message)) {
|
||||
@@ -1152,14 +1163,64 @@ void BaseWindow::SetTitleBarOverlay(const gin_helper::Dictionary& options,
|
||||
}
|
||||
#endif
|
||||
|
||||
// static
|
||||
void BaseWindow::ClearPersistedState(const std::string& window_name) {
|
||||
if (window_name.empty()) {
|
||||
LOG(WARNING) << "Cannot clear persisted window state: window name is empty";
|
||||
return;
|
||||
}
|
||||
|
||||
if (auto* browser_process =
|
||||
electron::ElectronBrowserMainParts::Get()->browser_process()) {
|
||||
DCHECK(browser_process);
|
||||
if (auto* prefs = browser_process->local_state()) {
|
||||
ScopedDictPrefUpdate update(prefs, electron::kWindowStates);
|
||||
|
||||
if (!update->Remove(window_name)) {
|
||||
LOG(WARNING) << "Window state '" << window_name
|
||||
<< "' not found, nothing to clear";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
gin_helper::WrappableBase* BaseWindow::New(gin::Arguments* const args) {
|
||||
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
|
||||
args->GetNext(&options);
|
||||
|
||||
std::string error_message;
|
||||
if (!IsWindowNameValid(options, &error_message)) {
|
||||
// Window name is already in use throw an error and do not create the window
|
||||
args->ThrowTypeError(error_message);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return new BaseWindow(args, options);
|
||||
}
|
||||
|
||||
// static
|
||||
bool BaseWindow::IsWindowNameValid(const gin_helper::Dictionary& options,
|
||||
std::string* error_message) {
|
||||
std::string window_name;
|
||||
if (options.Get(options::kName, &window_name) && !window_name.empty()) {
|
||||
// Check if window name is already in use by another window
|
||||
// Window names must be unique for state persistence to work correctly
|
||||
const auto& windows = electron::WindowList::GetWindows();
|
||||
bool name_in_use = std::any_of(windows.begin(), windows.end(),
|
||||
[&window_name](const auto* const window) {
|
||||
return window->GetName() == window_name;
|
||||
});
|
||||
|
||||
if (name_in_use) {
|
||||
*error_message = "Window name '" + window_name +
|
||||
"' is already in use. Window names must be unique.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// static
|
||||
void BaseWindow::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
@@ -1351,6 +1412,8 @@ void Initialize(v8::Local<v8::Object> exports,
|
||||
.ToLocalChecked());
|
||||
constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID);
|
||||
constructor.SetMethod("getAllWindows", &BaseWindow::GetAll);
|
||||
constructor.SetMethod("clearPersistedState",
|
||||
&BaseWindow::ClearPersistedState);
|
||||
|
||||
gin_helper::Dictionary dict(isolate, exports);
|
||||
dict.Set("BaseWindow", constructor);
|
||||
|
||||
@@ -46,6 +46,13 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
// Clears window state from the Local State JSON file in
|
||||
// app.getPath('userData') via PrefService.
|
||||
static void ClearPersistedState(const std::string& window_name);
|
||||
|
||||
static bool IsWindowNameValid(const gin_helper::Dictionary& options,
|
||||
std::string* error_message);
|
||||
|
||||
const NativeWindow* window() const { return window_.get(); }
|
||||
NativeWindow* window() { return window_.get(); }
|
||||
|
||||
@@ -97,6 +104,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
|
||||
const base::DictValue& details) override;
|
||||
void OnNewWindowForTab() override;
|
||||
void OnSystemContextMenu(int x, int y, bool* prevent_default) override;
|
||||
void OnWindowStateRestored() override;
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override;
|
||||
#endif
|
||||
|
||||
@@ -323,6 +323,13 @@ gin_helper::WrappableBase* BrowserWindow::New(gin_helper::ErrorThrower thrower,
|
||||
options = gin::Dictionary::CreateEmpty(args->isolate());
|
||||
}
|
||||
|
||||
std::string error_message;
|
||||
if (!IsWindowNameValid(options, &error_message)) {
|
||||
// Window name is already in use throw an error and do not create the window
|
||||
thrower.ThrowError(error_message);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return new BrowserWindow(args, options);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
#include "services/network/public/cpp/network_switches.h"
|
||||
#include "shell/browser/metrics/electron_metrics_service_client.h"
|
||||
#include "shell/browser/net/resolve_proxy_helper.h"
|
||||
#include "shell/common/electron_constants.h"
|
||||
#include "shell/common/electron_paths.h"
|
||||
#include "shell/common/thread_restrictions.h"
|
||||
|
||||
@@ -154,6 +155,8 @@ void BrowserProcessImpl::PostEarlyInitialization() {
|
||||
pref_registry.get());
|
||||
#endif
|
||||
|
||||
pref_registry->RegisterDictionaryPref(electron::kWindowStates);
|
||||
|
||||
in_memory_pref_store_ = base::MakeRefCounted<ValueMapPrefStore>();
|
||||
ApplyProxyModeFromCommandLine(in_memory_pref_store());
|
||||
prefs_factory.set_command_line_prefs(in_memory_pref_store());
|
||||
|
||||
@@ -9,21 +9,30 @@
|
||||
#include <vector>
|
||||
|
||||
#include "base/memory/ptr_util.h"
|
||||
#include "base/memory/raw_ptr.h"
|
||||
#include "base/strings/utf_string_conversions.h"
|
||||
#include "base/values.h"
|
||||
#include "components/prefs/pref_service.h"
|
||||
#include "components/prefs/scoped_user_pref_update.h"
|
||||
#include "content/public/browser/web_contents_user_data.h"
|
||||
#include "include/core/SkColor.h"
|
||||
#include "shell/browser/background_throttling_source.h"
|
||||
#include "shell/browser/browser.h"
|
||||
#include "shell/browser/browser_process_impl.h"
|
||||
#include "shell/browser/draggable_region_provider.h"
|
||||
#include "shell/browser/electron_browser_main_parts.h"
|
||||
#include "shell/browser/ui/drag_util.h"
|
||||
#include "shell/browser/window_list.h"
|
||||
#include "shell/common/color_util.h"
|
||||
#include "shell/common/electron_constants.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/persistent_dictionary.h"
|
||||
#include "shell/common/options_switches.h"
|
||||
#include "ui/base/hit_test.h"
|
||||
#include "ui/compositor/compositor.h"
|
||||
#include "ui/display/display.h"
|
||||
#include "ui/display/screen.h"
|
||||
#include "ui/display/types/display_constants.h"
|
||||
#include "ui/views/widget/widget.h"
|
||||
|
||||
#if !BUILDFLAG(IS_MAC)
|
||||
@@ -66,6 +75,15 @@ struct Converter<electron::NativeWindow::TitleBarStyle> {
|
||||
|
||||
namespace electron {
|
||||
|
||||
namespace {
|
||||
// Check if display is fake (default display ID) or has invalid dimensions
|
||||
bool hasInvalidDisplay(const display::Display& display) {
|
||||
return display.id() == display::kDefaultDisplayId ||
|
||||
display.size().width() == 0 || display.size().height() == 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NativeWindow::NativeWindow(const int32_t base_window_id,
|
||||
const gin_helper::Dictionary& options,
|
||||
NativeWindow* parent)
|
||||
@@ -88,6 +106,38 @@ NativeWindow::NativeWindow(const int32_t base_window_id,
|
||||
options.Get(options::kVibrancyType, &vibrancy_);
|
||||
#endif
|
||||
|
||||
options.Get(options::kName, &window_name_);
|
||||
|
||||
if (gin_helper::Dictionary persistence_options;
|
||||
options.Get(options::kWindowStatePersistence, &persistence_options)) {
|
||||
// Restore bounds by default
|
||||
restore_bounds_ = true;
|
||||
persistence_options.Get(options::kBounds, &restore_bounds_);
|
||||
// Restore display mode by default
|
||||
restore_display_mode_ = true;
|
||||
persistence_options.Get(options::kDisplayMode, &restore_display_mode_);
|
||||
window_state_persistence_enabled_ = true;
|
||||
} else if (bool flag; options.Get(options::kWindowStatePersistence, &flag)) {
|
||||
restore_bounds_ = flag;
|
||||
restore_display_mode_ = flag;
|
||||
window_state_persistence_enabled_ = flag;
|
||||
}
|
||||
|
||||
// Initialize prefs_ to save/restore window bounds if we have a valid window
|
||||
// name and window state persistence is enabled.
|
||||
if (window_state_persistence_enabled_ && !window_name_.empty()) {
|
||||
// Move this out if there's a need to initialize prefs_ for other features
|
||||
if (auto* browser_process =
|
||||
electron::ElectronBrowserMainParts::Get()->browser_process()) {
|
||||
DCHECK(browser_process);
|
||||
prefs_ = browser_process->local_state();
|
||||
}
|
||||
} else if (window_state_persistence_enabled_ && window_name_.empty()) {
|
||||
window_state_persistence_enabled_ = false;
|
||||
LOG(WARNING) << "Window state persistence enabled but no window name "
|
||||
"provided. Window state will not be persisted.";
|
||||
}
|
||||
|
||||
if (gin_helper::Dictionary dict;
|
||||
options.Get(options::ktitleBarOverlay, &dict)) {
|
||||
titlebar_overlay_ = true;
|
||||
@@ -194,7 +244,14 @@ void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
|
||||
options.Get(options::kFullScreenable, &fullscreenable);
|
||||
SetFullScreenable(fullscreenable);
|
||||
|
||||
if (fullscreen)
|
||||
// Restore window state (bounds and display mode) at this point in
|
||||
// initialization. We deliberately restore bounds before display modes
|
||||
// (fullscreen/kiosk) since the target display for these states depends on the
|
||||
// window's initial bounds. Also, restoring here ensures we respect min/max
|
||||
// width/height and fullscreenable constraints.
|
||||
RestoreWindowState(options);
|
||||
|
||||
if (fullscreen && !restore_display_mode_)
|
||||
SetFullScreen(true);
|
||||
|
||||
if (bool val; options.Get(options::kResizable, &val))
|
||||
@@ -203,7 +260,8 @@ void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
|
||||
if (bool val; options.Get(options::kSkipTaskbar, &val))
|
||||
SetSkipTaskbar(val);
|
||||
|
||||
if (bool val; options.Get(options::kKiosk, &val) && val)
|
||||
if (bool val;
|
||||
options.Get(options::kKiosk, &val) && val && !restore_display_mode_)
|
||||
SetKiosk(val);
|
||||
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
@@ -223,7 +281,9 @@ void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
|
||||
SetBackgroundColor(background_color);
|
||||
|
||||
SetTitle(options.ValueOrDefault(options::kTitle, Browser::Get()->GetName()));
|
||||
|
||||
// Save updated window state after restoration adjustments are complete if
|
||||
// any.
|
||||
SaveWindowState();
|
||||
// Then show it.
|
||||
if (options.ValueOrDefault(options::kShow, true))
|
||||
Show();
|
||||
@@ -524,6 +584,12 @@ void NativeWindow::NotifyWindowHide() {
|
||||
}
|
||||
|
||||
void NativeWindow::NotifyWindowMaximize() {
|
||||
// A restoration-initiated maximize transition has completed; lift the guard
|
||||
// so subsequent state changes are persisted again.
|
||||
if (awaiting_restore_display_mode_transition_) {
|
||||
awaiting_restore_display_mode_transition_ = false;
|
||||
is_being_restored_ = false;
|
||||
}
|
||||
observers_.Notify(&NativeWindowObserver::OnWindowMaximize);
|
||||
}
|
||||
|
||||
@@ -570,6 +636,13 @@ void NativeWindow::NotifyWindowMoved() {
|
||||
}
|
||||
|
||||
void NativeWindow::NotifyWindowEnterFullScreen() {
|
||||
// A restoration-initiated fullscreen (or kiosk, which routes through
|
||||
// fullscreen) transition has completed; lift the guard so subsequent state
|
||||
// changes are persisted again.
|
||||
if (awaiting_restore_display_mode_transition_) {
|
||||
awaiting_restore_display_mode_transition_ = false;
|
||||
is_being_restored_ = false;
|
||||
}
|
||||
NotifyLayoutWindowControlsOverlay();
|
||||
observers_.Notify(&NativeWindowObserver::OnWindowEnterFullScreen);
|
||||
}
|
||||
@@ -636,6 +709,10 @@ void NativeWindow::NotifyLayoutWindowControlsOverlay() {
|
||||
*bounds);
|
||||
}
|
||||
|
||||
void NativeWindow::NotifyWindowStateRestored() {
|
||||
observers_.Notify(&NativeWindowObserver::OnWindowStateRestored);
|
||||
}
|
||||
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
void NativeWindow::NotifyWindowMessage(UINT message,
|
||||
WPARAM w_param,
|
||||
@@ -740,10 +817,14 @@ void NativeWindow::SetAccessibleTitle(const std::string& title) {
|
||||
WidgetDelegate::SetAccessibleTitle(base::UTF8ToUTF16(title));
|
||||
}
|
||||
|
||||
std::string NativeWindow::GetAccessibleTitle() {
|
||||
std::string NativeWindow::GetAccessibleTitle() const {
|
||||
return base::UTF16ToUTF8(GetAccessibleWindowTitle());
|
||||
}
|
||||
|
||||
std::string NativeWindow::GetName() const {
|
||||
return window_name_;
|
||||
}
|
||||
|
||||
void NativeWindow::HandlePendingFullscreenTransitions() {
|
||||
if (pending_transitions_.empty()) {
|
||||
set_fullscreen_transition_type(FullScreenTransitionType::kNone);
|
||||
@@ -776,6 +857,282 @@ bool NativeWindow::IsTranslucent() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
void NativeWindow::DebouncedSaveWindowState() {
|
||||
save_window_state_timer_.Start(
|
||||
FROM_HERE, base::Milliseconds(200),
|
||||
base::BindOnce(&NativeWindow::SaveWindowState, base::Unretained(this)));
|
||||
}
|
||||
|
||||
void NativeWindow::SaveWindowState() {
|
||||
if (!window_state_persistence_enabled_ || is_being_restored_ ||
|
||||
is_transitioning_fullscreen())
|
||||
return;
|
||||
|
||||
gfx::Rect bounds = GetBounds();
|
||||
|
||||
if (bounds.width() == 0 || bounds.height() == 0) {
|
||||
LOG(WARNING) << "Window state not saved - window bounds are invalid";
|
||||
return;
|
||||
}
|
||||
|
||||
const display::Screen* screen = display::Screen::Get();
|
||||
DCHECK(screen);
|
||||
// GetDisplayMatching returns a fake display with 1920x1080 resolution at
|
||||
// (0,0) when no physical displays are attached.
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:ui/display/display.cc;l=184;drc=e4f1aef5f3ec30a28950d766612cc2c04c822c71
|
||||
const display::Display display = screen->GetDisplayMatching(bounds);
|
||||
|
||||
// Skip window state persistence when display has invalid dimensions (0x0) or
|
||||
// is fake (ID 0xFF). Invalid displays could cause incorrect window bounds to
|
||||
// be saved, leading to positioning issues during restoration.
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:ui/display/types/display_constants.h;l=28;drc=e4f1aef5f3ec30a28950d766612cc2c04c822c71
|
||||
if (hasInvalidDisplay(display)) {
|
||||
LOG(WARNING)
|
||||
<< "Window state not saved - no physical display attached or current "
|
||||
"display has invalid bounds";
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedDictPrefUpdate update(prefs_, electron::kWindowStates);
|
||||
const base::DictValue* existing_prefs = update->FindDict(window_name_);
|
||||
|
||||
// When the window is in a special display mode (fullscreen, kiosk, or
|
||||
// maximized), save the previously stored window bounds instead of
|
||||
// the current bounds. This ensures that when the window is restored, it can
|
||||
// be restored to its original position and size if display mode is not
|
||||
// preserved via windowStatePersistence.
|
||||
if (!IsNormal() && existing_prefs) {
|
||||
std::optional<int> left = existing_prefs->FindInt(electron::kLeft);
|
||||
std::optional<int> top = existing_prefs->FindInt(electron::kTop);
|
||||
std::optional<int> right = existing_prefs->FindInt(electron::kRight);
|
||||
std::optional<int> bottom = existing_prefs->FindInt(electron::kBottom);
|
||||
|
||||
if (left && top && right && bottom) {
|
||||
bounds = gfx::Rect(*left, *top, *right - *left, *bottom - *top);
|
||||
}
|
||||
}
|
||||
|
||||
base::DictValue window_preferences;
|
||||
window_preferences.Set(electron::kLeft, bounds.x());
|
||||
window_preferences.Set(electron::kTop, bounds.y());
|
||||
window_preferences.Set(electron::kRight, bounds.right());
|
||||
window_preferences.Set(electron::kBottom, bounds.bottom());
|
||||
|
||||
window_preferences.Set(electron::kMaximized, IsMaximized());
|
||||
window_preferences.Set(electron::kFullscreen, IsFullscreen());
|
||||
window_preferences.Set(electron::kKiosk, IsKiosk());
|
||||
|
||||
gfx::Rect work_area = display.work_area();
|
||||
|
||||
window_preferences.Set(electron::kWorkAreaLeft, work_area.x());
|
||||
window_preferences.Set(electron::kWorkAreaTop, work_area.y());
|
||||
window_preferences.Set(electron::kWorkAreaRight, work_area.right());
|
||||
window_preferences.Set(electron::kWorkAreaBottom, work_area.bottom());
|
||||
|
||||
update->Set(window_name_, std::move(window_preferences));
|
||||
}
|
||||
|
||||
void NativeWindow::FlushWindowState() {
|
||||
// Window destroyed before Show()/ShowInactive() ever ran the deferred
|
||||
// restore: drop the pending callback and clear the guard so the final save
|
||||
// isn't suppressed. During a real restoration transition the callback has
|
||||
// already been moved out, so this is a no-op and transitional bounds stay
|
||||
// suppressed.
|
||||
if (restore_display_mode_callback_) {
|
||||
restore_display_mode_callback_.Reset();
|
||||
is_being_restored_ = false;
|
||||
awaiting_restore_display_mode_transition_ = false;
|
||||
}
|
||||
|
||||
if (save_window_state_timer_.IsRunning()) {
|
||||
save_window_state_timer_.FireNow();
|
||||
} else {
|
||||
SaveWindowState();
|
||||
}
|
||||
}
|
||||
|
||||
void NativeWindow::RestoreWindowState(const gin_helper::Dictionary& options) {
|
||||
if (!window_state_persistence_enabled_)
|
||||
return;
|
||||
|
||||
const base::Value& value = prefs_->GetValue(electron::kWindowStates);
|
||||
const base::DictValue* window_preferences =
|
||||
value.is_dict() ? value.GetDict().FindDict(window_name_) : nullptr;
|
||||
|
||||
if (!window_preferences)
|
||||
return;
|
||||
|
||||
std::optional<int> saved_left = window_preferences->FindInt(electron::kLeft);
|
||||
std::optional<int> saved_top = window_preferences->FindInt(electron::kTop);
|
||||
std::optional<int> saved_right =
|
||||
window_preferences->FindInt(electron::kRight);
|
||||
std::optional<int> saved_bottom =
|
||||
window_preferences->FindInt(electron::kBottom);
|
||||
|
||||
std::optional<int> work_area_left =
|
||||
window_preferences->FindInt(electron::kWorkAreaLeft);
|
||||
std::optional<int> work_area_top =
|
||||
window_preferences->FindInt(electron::kWorkAreaTop);
|
||||
std::optional<int> work_area_right =
|
||||
window_preferences->FindInt(electron::kWorkAreaRight);
|
||||
std::optional<int> work_area_bottom =
|
||||
window_preferences->FindInt(electron::kWorkAreaBottom);
|
||||
|
||||
if (!saved_left || !saved_top || !saved_right || !saved_bottom ||
|
||||
!work_area_left || !work_area_top || !work_area_right ||
|
||||
!work_area_bottom) {
|
||||
LOG(WARNING) << "Window state not restored - corrupted values found";
|
||||
return;
|
||||
}
|
||||
|
||||
gfx::Rect saved_bounds =
|
||||
gfx::Rect(*saved_left, *saved_top, *saved_right - *saved_left,
|
||||
*saved_bottom - *saved_top);
|
||||
|
||||
display::Screen* screen = display::Screen::Get();
|
||||
DCHECK(screen);
|
||||
|
||||
// Set the primary display as the target display for restoration.
|
||||
display::Display display = screen->GetPrimaryDisplay();
|
||||
|
||||
// We identify the display with the minimal Manhattan distance to the saved
|
||||
// bounds and set it as the target display for restoration.
|
||||
int min_displacement = std::numeric_limits<int>::max();
|
||||
|
||||
for (const auto& candidate : screen->GetAllDisplays()) {
|
||||
gfx::Rect test_bounds = saved_bounds;
|
||||
test_bounds.AdjustToFit(candidate.work_area());
|
||||
int displacement = std::abs(test_bounds.x() - saved_bounds.x()) +
|
||||
std::abs(test_bounds.y() - saved_bounds.y());
|
||||
|
||||
if (displacement < min_displacement) {
|
||||
min_displacement = displacement;
|
||||
display = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip window state restoration if current display has invalid dimensions or
|
||||
// is fake. Restoring from invalid displays (0x0) or fake displays (ID 0xFF)
|
||||
// could cause incorrect window positioning when later moved to real displays.
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:ui/display/types/display_constants.h;l=28;drc=e4f1aef5f3ec30a28950d766612cc2c04c822c71
|
||||
if (hasInvalidDisplay(display)) {
|
||||
LOG(WARNING) << "Window state not restored - no physical display attached "
|
||||
"or current display has invalid bounds";
|
||||
return;
|
||||
}
|
||||
|
||||
gfx::Rect saved_work_area = gfx::Rect(*work_area_left, *work_area_top,
|
||||
*work_area_right - *work_area_left,
|
||||
*work_area_bottom - *work_area_top);
|
||||
|
||||
// Set this to true before RestoreBounds to prevent SaveWindowState from being
|
||||
// inadvertently triggered during the restoration process.
|
||||
is_being_restored_ = true;
|
||||
|
||||
if (restore_bounds_) {
|
||||
RestoreBounds(display, saved_work_area, saved_bounds);
|
||||
}
|
||||
|
||||
if (restore_display_mode_) {
|
||||
// The display-mode change (kiosk/fullscreen/maximize) runs from Show()/
|
||||
// ShowInactive() via FlushPendingDisplayMode(). It triggers resize/move
|
||||
// events that schedule DebouncedSaveWindowState. Keep is_being_restored_
|
||||
// true until the transition completes so transitional bounds aren't
|
||||
// persisted over the saved ones. Because these transitions are async on
|
||||
// macOS, the reset is deferred to the matching Notify* observer
|
||||
// (NotifyWindowEnterFullScreen/NotifyWindowMaximize) rather than reset
|
||||
// synchronously here.
|
||||
restore_display_mode_callback_ = base::BindOnce(
|
||||
[](NativeWindow* window, base::DictValue prefs) {
|
||||
bool transition_initiated = true;
|
||||
if (auto kiosk = prefs.FindBool(electron::kKiosk); kiosk && *kiosk) {
|
||||
window->awaiting_restore_display_mode_transition_ = true;
|
||||
window->SetKiosk(true);
|
||||
} else if (auto fs = prefs.FindBool(electron::kFullscreen);
|
||||
fs && *fs) {
|
||||
window->awaiting_restore_display_mode_transition_ = true;
|
||||
window->SetFullScreen(true);
|
||||
} else if (auto max = prefs.FindBool(electron::kMaximized);
|
||||
max && *max) {
|
||||
window->awaiting_restore_display_mode_transition_ = true;
|
||||
window->Maximize();
|
||||
} else {
|
||||
transition_initiated = false;
|
||||
}
|
||||
// No display-mode transition to wait on (saved state was normal):
|
||||
// lift the guard immediately.
|
||||
if (!transition_initiated)
|
||||
window->is_being_restored_ = false;
|
||||
},
|
||||
base::Unretained(this), window_preferences->Clone());
|
||||
} else {
|
||||
is_being_restored_ = false;
|
||||
}
|
||||
|
||||
NotifyWindowStateRestored();
|
||||
}
|
||||
|
||||
void NativeWindow::FlushPendingDisplayMode() {
|
||||
if (restore_display_mode_callback_) {
|
||||
std::move(restore_display_mode_callback_).Run();
|
||||
}
|
||||
}
|
||||
|
||||
// This function is similar to Chromium's window bounds adjustment logic
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/ui/window_sizer/window_sizer.cc;l=350;drc=0ec56065ba588552f21633aa47280ba02c3cd160
|
||||
void NativeWindow::RestoreBounds(const display::Display& display,
|
||||
const gfx::Rect& saved_work_area,
|
||||
gfx::Rect& saved_bounds) {
|
||||
if (saved_bounds.width() == 0 || saved_bounds.height() == 0) {
|
||||
LOG(WARNING) << "Window bounds not restored - values are invalid";
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure that the window is at least kMinVisibleHeight * kMinVisibleWidth.
|
||||
saved_bounds.set_height(std::max(kMinVisibleHeight, saved_bounds.height()));
|
||||
saved_bounds.set_width(std::max(kMinVisibleWidth, saved_bounds.width()));
|
||||
|
||||
const gfx::Rect work_area = display.work_area();
|
||||
// Ensure that the title bar is not above the work area.
|
||||
if (saved_bounds.y() < work_area.y()) {
|
||||
saved_bounds.set_y(work_area.y());
|
||||
}
|
||||
|
||||
// Reposition and resize the bounds if the saved_work_area is different from
|
||||
// the current work area and the current work area doesn't completely contain
|
||||
// the bounds.
|
||||
if (!saved_work_area.IsEmpty() && saved_work_area != work_area &&
|
||||
!work_area.Contains(saved_bounds)) {
|
||||
saved_bounds.AdjustToFit(work_area);
|
||||
}
|
||||
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
// On mac, we want to be aggressive about repositioning windows that are
|
||||
// partially offscreen. If the window is partially offscreen horizontally,
|
||||
// snap to the nearest edge of the work area. This call also adjusts the
|
||||
// height, width if needed to make the window fully visible.
|
||||
saved_bounds.AdjustToFit(work_area);
|
||||
#else
|
||||
// On non-Mac platforms, we are less aggressive about repositioning. Simply
|
||||
// ensure that at least kMinVisibleWidth * kMinVisibleHeight is visible
|
||||
|
||||
const int min_y = work_area.y() + kMinVisibleHeight - saved_bounds.height();
|
||||
const int min_x = work_area.x() + kMinVisibleWidth - saved_bounds.width();
|
||||
const int max_y = work_area.bottom() - kMinVisibleHeight;
|
||||
const int max_x = work_area.right() - kMinVisibleWidth;
|
||||
// Reposition and resize the bounds to make it fully visible inside the work
|
||||
// area. `min_x >= max_x` happens when work area and bounds are both small.
|
||||
if (min_x >= max_x || min_y >= max_y) {
|
||||
saved_bounds.AdjustToFit(work_area);
|
||||
} else {
|
||||
saved_bounds.set_y(std::clamp(saved_bounds.y(), min_y, max_y));
|
||||
saved_bounds.set_x(std::clamp(saved_bounds.x(), min_x, max_x));
|
||||
}
|
||||
#endif // BUILDFLAG(IS_MAC)
|
||||
|
||||
SetBounds(saved_bounds, false);
|
||||
}
|
||||
|
||||
// static
|
||||
bool NativeWindow::PlatformHasClientFrame() {
|
||||
#if defined(USE_OZONE)
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "base/observer_list.h"
|
||||
#include "base/strings/cstring_view.h"
|
||||
#include "base/supports_user_data.h"
|
||||
#include "base/timer/timer.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"
|
||||
@@ -26,6 +28,7 @@
|
||||
|
||||
class SkRegion;
|
||||
class DraggableRegionProvider;
|
||||
class PrefService;
|
||||
|
||||
namespace input {
|
||||
struct NativeWebKeyboardEvent;
|
||||
@@ -165,9 +168,11 @@ class NativeWindow : public views::WidgetDelegate {
|
||||
void SetTitle(std::string_view title);
|
||||
[[nodiscard]] std::string GetTitle() const;
|
||||
|
||||
[[nodiscard]] std::string GetName() const;
|
||||
|
||||
// Ability to augment the window title for the screen readers.
|
||||
void SetAccessibleTitle(const std::string& title);
|
||||
std::string GetAccessibleTitle();
|
||||
[[nodiscard]] std::string GetAccessibleTitle() const;
|
||||
|
||||
virtual void FlashFrame(bool flash) = 0;
|
||||
virtual void SetSkipTaskbar(bool skip) = 0;
|
||||
@@ -340,6 +345,7 @@ class NativeWindow : public views::WidgetDelegate {
|
||||
void NotifyNewWindowForTab();
|
||||
void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default);
|
||||
void NotifyLayoutWindowControlsOverlay();
|
||||
void NotifyWindowStateRestored();
|
||||
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param);
|
||||
@@ -438,6 +444,28 @@ class NativeWindow : public views::WidgetDelegate {
|
||||
|
||||
[[nodiscard]] auto base_window_id() const { return base_window_id_; }
|
||||
|
||||
// Saves current window state to the Local State JSON file in
|
||||
// app.getPath('userData') via PrefService.
|
||||
// This does NOT immediately write to disk - it updates the in-memory
|
||||
// preference store and queues an asynchronous write operation. The actual
|
||||
// disk write is batched and flushed later.
|
||||
void SaveWindowState();
|
||||
void DebouncedSaveWindowState();
|
||||
// Flushes save_window_state_timer_ that was queued by
|
||||
// DebouncedSaveWindowState. This does NOT flush the actual disk write.
|
||||
void FlushWindowState();
|
||||
|
||||
// Restores window state - bounds first and then display mode.
|
||||
void RestoreWindowState(const gin_helper::Dictionary& options);
|
||||
// Applies saved bounds to the window.
|
||||
void RestoreBounds(const display::Display& display,
|
||||
const gfx::Rect& saved_work_area,
|
||||
gfx::Rect& saved_bounds);
|
||||
// Flushes pending display mode restoration (fullscreen, maximized, kiosk)
|
||||
// that was deferred during initialization to respect show=false. This
|
||||
// consumes and clears the restore_display_mode_callback_.
|
||||
void FlushPendingDisplayMode();
|
||||
|
||||
protected:
|
||||
NativeWindow(int32_t base_window_id,
|
||||
const gin_helper::Dictionary& options,
|
||||
@@ -503,6 +531,10 @@ class NativeWindow : public views::WidgetDelegate {
|
||||
// ID of the api::BaseWindow that owns this NativeWindow.
|
||||
const int32_t base_window_id_;
|
||||
|
||||
// Identifier for the window provided by the application.
|
||||
// Used by Electron internally for features such as state persistence.
|
||||
std::string window_name_;
|
||||
|
||||
// The "titleBarStyle" option.
|
||||
const TitleBarStyle title_bar_style_;
|
||||
|
||||
@@ -564,6 +596,37 @@ class NativeWindow : public views::WidgetDelegate {
|
||||
|
||||
gfx::Rect overlay_rect_;
|
||||
|
||||
// Flag to prevent SaveWindowState calls during window restoration.
|
||||
bool is_being_restored_ = false;
|
||||
|
||||
// True while a restoration-initiated display-mode transition
|
||||
// (fullscreen/maximize/kiosk) is in flight. Cleared from the matching
|
||||
// Notify* observer once the (possibly async) transition completes.
|
||||
bool awaiting_restore_display_mode_transition_ = false;
|
||||
|
||||
// The boolean parsing of the "windowStatePersistence" option
|
||||
bool window_state_persistence_enabled_ = false;
|
||||
|
||||
// PrefService is used to persist window bounds and state.
|
||||
// Only populated when windowStatePersistence is enabled and window has a
|
||||
// valid name.
|
||||
raw_ptr<PrefService> prefs_ = nullptr;
|
||||
|
||||
// Whether to restore bounds.
|
||||
bool restore_bounds_ = false;
|
||||
// Whether to restore display mode.
|
||||
bool restore_display_mode_ = false;
|
||||
// Callback to restore display mode.
|
||||
base::OnceCallback<void()> restore_display_mode_callback_;
|
||||
|
||||
// Timer to debounce window state saving operations.
|
||||
base::OneShotTimer save_window_state_timer_;
|
||||
|
||||
// Minimum height of the visible part of a window.
|
||||
const int kMinVisibleHeight = 100;
|
||||
// Minimum width of the visible part of a window.
|
||||
const int kMinVisibleWidth = 100;
|
||||
|
||||
raw_ptr<InspectableWebContentsView> primary_web_contents_view_ = nullptr;
|
||||
|
||||
base::WeakPtrFactory<NativeWindow> weak_factory_{this};
|
||||
|
||||
@@ -470,6 +470,8 @@ void NativeWindowMac::Show() {
|
||||
return;
|
||||
}
|
||||
|
||||
FlushPendingDisplayMode();
|
||||
|
||||
set_wants_to_be_visible(true);
|
||||
|
||||
// Reattach the window to the parent to actually show it.
|
||||
@@ -484,6 +486,8 @@ void NativeWindowMac::Show() {
|
||||
}
|
||||
|
||||
void NativeWindowMac::ShowInactive() {
|
||||
FlushPendingDisplayMode();
|
||||
|
||||
set_wants_to_be_visible(true);
|
||||
|
||||
// Reattach the window to the parent to actually show it.
|
||||
|
||||
@@ -110,6 +110,8 @@ class NativeWindowObserver : public base::CheckedObserver {
|
||||
virtual void OnExecuteAppCommand(std::string_view command_name) {}
|
||||
|
||||
virtual void UpdateWindowControlsOverlay(const gfx::Rect& bounding_rect) {}
|
||||
|
||||
virtual void OnWindowStateRestored() {}
|
||||
};
|
||||
|
||||
} // namespace electron
|
||||
|
||||
@@ -592,6 +592,8 @@ void NativeWindowViews::Show() {
|
||||
if (is_modal() && NativeWindow::parent() && !widget()->IsVisible())
|
||||
static_cast<NativeWindowViews*>(parent())->IncrementChildModals();
|
||||
|
||||
FlushPendingDisplayMode();
|
||||
|
||||
widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect());
|
||||
|
||||
// explicitly focus the window
|
||||
@@ -611,6 +613,8 @@ void NativeWindowViews::Show() {
|
||||
}
|
||||
|
||||
void NativeWindowViews::ShowInactive() {
|
||||
FlushPendingDisplayMode();
|
||||
|
||||
widget()->ShowInactive();
|
||||
|
||||
NotifyWindowShow();
|
||||
|
||||
@@ -21,6 +21,23 @@ inline constexpr std::string_view kDeviceVendorIdKey = "vendorId";
|
||||
inline constexpr std::string_view kDeviceProductIdKey = "productId";
|
||||
inline constexpr std::string_view kDeviceSerialNumberKey = "serialNumber";
|
||||
|
||||
// Window state preference keys
|
||||
inline constexpr std::string_view kLeft = "left";
|
||||
inline constexpr std::string_view kTop = "top";
|
||||
inline constexpr std::string_view kRight = "right";
|
||||
inline constexpr std::string_view kBottom = "bottom";
|
||||
|
||||
inline constexpr std::string_view kMaximized = "maximized";
|
||||
inline constexpr std::string_view kFullscreen = "fullscreen";
|
||||
inline constexpr std::string_view kKiosk = "kiosk";
|
||||
|
||||
inline constexpr std::string_view kWorkAreaLeft = "workAreaLeft";
|
||||
inline constexpr std::string_view kWorkAreaTop = "workAreaTop";
|
||||
inline constexpr std::string_view kWorkAreaRight = "workAreaRight";
|
||||
inline constexpr std::string_view kWorkAreaBottom = "workAreaBottom";
|
||||
|
||||
inline constexpr std::string_view kWindowStates = "windowStates";
|
||||
|
||||
inline constexpr base::cstring_view kRunAsNode = "ELECTRON_RUN_AS_NODE";
|
||||
|
||||
// Per-profile UUID to distinguish global shortcut sessions for
|
||||
|
||||
@@ -107,6 +107,19 @@ inline constexpr std::string_view kFocusable = "focusable";
|
||||
// The WebPreferences.
|
||||
inline constexpr std::string_view kWebPreferences = "webPreferences";
|
||||
|
||||
// Window state persistence for BaseWindow
|
||||
inline constexpr std::string_view kWindowStatePersistence =
|
||||
"windowStatePersistence";
|
||||
|
||||
// Identifier for the window provided by the application
|
||||
inline constexpr std::string_view kName = "name";
|
||||
|
||||
// Whether to save the window bounds
|
||||
inline constexpr std::string_view kBounds = "bounds";
|
||||
|
||||
// Whether to save the window display mode
|
||||
inline constexpr std::string_view kDisplayMode = "displayMode";
|
||||
|
||||
// Add a vibrancy effect to the browser window
|
||||
inline constexpr std::string_view kVibrancyType = "vibrancy";
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-close-save',
|
||||
windowStatePersistence: true,
|
||||
show: false
|
||||
});
|
||||
|
||||
w.on('close', () => {
|
||||
app.quit();
|
||||
});
|
||||
|
||||
w.close();
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-fullscreen-save',
|
||||
windowStatePersistence: true
|
||||
});
|
||||
|
||||
w.on('enter-full-screen', () => {
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
w.setFullScreen(true);
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-kiosk-save',
|
||||
windowStatePersistence: true
|
||||
});
|
||||
|
||||
w.on('enter-full-screen', () => {
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
w.setKiosk(true);
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
const prefsPath = path.join(sharedUserData, 'Local State');
|
||||
|
||||
const waitForPrefsFile = async () => {
|
||||
while (!fs.existsSync(prefsPath)) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
};
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-main-thread-busy',
|
||||
windowStatePersistence: true,
|
||||
show: false
|
||||
});
|
||||
|
||||
await waitForPrefsFile();
|
||||
const initialMtime = fs.statSync(prefsPath).mtimeMs;
|
||||
|
||||
const moved = new Promise((resolve) => w.once('move', resolve));
|
||||
w.setPosition(100, 100);
|
||||
await moved;
|
||||
|
||||
const startTime = Date.now();
|
||||
while (Date.now() - startTime < 25_000);
|
||||
|
||||
const finalMtime = fs.statSync(prefsPath).mtimeMs;
|
||||
const exitCode = finalMtime === initialMtime ? 0 : 1;
|
||||
|
||||
w.destroy();
|
||||
app.exit(exitCode);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-maximize-save',
|
||||
windowStatePersistence: true
|
||||
});
|
||||
|
||||
w.on('maximize', () => {
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
w.maximize();
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-minimize-save',
|
||||
windowStatePersistence: true
|
||||
});
|
||||
|
||||
w.on('minimize', () => {
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
w.minimize();
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-move-save',
|
||||
windowStatePersistence: true,
|
||||
show: false
|
||||
});
|
||||
|
||||
w.setPosition(100, 150);
|
||||
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-resize-save',
|
||||
windowStatePersistence: true,
|
||||
show: false
|
||||
});
|
||||
|
||||
w.setSize(500, 400);
|
||||
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(() => {
|
||||
const w = new BrowserWindow({
|
||||
width: 400,
|
||||
height: 300,
|
||||
name: 'test-window-state-schema',
|
||||
windowStatePersistence: true,
|
||||
show: true
|
||||
});
|
||||
|
||||
w.close();
|
||||
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 1000);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
const { app, BrowserWindow, screen } = require('electron');
|
||||
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const sharedUserData = path.join(os.tmpdir(), 'electron-window-state-test');
|
||||
app.setPath('userData', sharedUserData);
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const primaryDisplay = screen.getPrimaryDisplay();
|
||||
const workArea = primaryDisplay.workArea;
|
||||
|
||||
const maxWidth = Math.max(200, Math.floor(workArea.width * 0.8));
|
||||
const maxHeight = Math.max(150, Math.floor(workArea.height * 0.8));
|
||||
const windowWidth = Math.min(400, maxWidth);
|
||||
const windowHeight = Math.min(300, maxHeight);
|
||||
|
||||
const w = new BrowserWindow({
|
||||
width: windowWidth,
|
||||
height: windowHeight,
|
||||
name: 'test-work-area-primary',
|
||||
windowStatePersistence: true
|
||||
});
|
||||
|
||||
// Center the window on the primary display to prevent overflow
|
||||
const centerX = workArea.x + Math.floor((workArea.width - windowWidth) / 2);
|
||||
const centerY = workArea.y + Math.floor((workArea.height - windowHeight) / 2);
|
||||
|
||||
w.setPosition(centerX, centerY);
|
||||
|
||||
w.on('close', () => {
|
||||
app.quit();
|
||||
});
|
||||
|
||||
w.close();
|
||||
|
||||
// Timeout of 10s to ensure app exits
|
||||
setTimeout(() => {
|
||||
app.quit();
|
||||
}, 10000);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"targets": [{
|
||||
"target_name": "virtual_display",
|
||||
"conditions": [
|
||||
['OS=="mac"', {
|
||||
"sources": [
|
||||
"src/addon.mm",
|
||||
"src/VirtualDisplayBridge.m"
|
||||
],
|
||||
"include_dirs": [
|
||||
"<!@(node -p \"require('node-addon-api').include\")",
|
||||
"include"
|
||||
],
|
||||
"dependencies": [
|
||||
"<!(node -p \"require('node-addon-api').gyp\")"
|
||||
],
|
||||
"defines": [
|
||||
"NODE_ADDON_API_CPP_EXCEPTIONS"
|
||||
],
|
||||
"cflags!": [ "-fno-exceptions" ],
|
||||
"cflags_cc!": [ "-fno-exceptions" ],
|
||||
"xcode_settings": {
|
||||
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
|
||||
"CLANG_ENABLE_OBJC_ARC": "YES",
|
||||
"CLANG_CXX_LIBRARY": "libc++",
|
||||
"MACOSX_DEPLOYMENT_TARGET": "11.0",
|
||||
"OTHER_CFLAGS": [
|
||||
"-fobjc-arc"
|
||||
]
|
||||
}
|
||||
}]
|
||||
]
|
||||
}]
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
#ifndef VirtualDisplayBridge_h
|
||||
#define VirtualDisplayBridge_h
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface VirtualDisplayBridge : NSObject
|
||||
|
||||
+ (NSInteger)create:(int)width height:(int)height x:(int)x y:(int)y;
|
||||
+ (BOOL)destroy:(NSInteger)displayId;
|
||||
+ (BOOL)forceCleanup;
|
||||
|
||||
@end
|
||||
|
||||
@interface CGVirtualDisplay : NSObject {
|
||||
unsigned int _vendorID;
|
||||
unsigned int _productID;
|
||||
unsigned int _serialNum;
|
||||
NSString* _name;
|
||||
struct CGSize _sizeInMillimeters;
|
||||
unsigned int _maxPixelsWide;
|
||||
unsigned int _maxPixelsHigh;
|
||||
struct CGPoint _redPrimary;
|
||||
struct CGPoint _greenPrimary;
|
||||
struct CGPoint _bluePrimary;
|
||||
struct CGPoint _whitePoint;
|
||||
id _queue;
|
||||
id _terminationHandler;
|
||||
void* _client;
|
||||
unsigned int _displayID;
|
||||
unsigned int _hiDPI;
|
||||
NSArray* _modes;
|
||||
unsigned int _serverRPC_port;
|
||||
unsigned int _proxyRPC_port;
|
||||
unsigned int _clientHandler_port;
|
||||
}
|
||||
|
||||
@property(readonly, nonatomic) NSArray* modes;
|
||||
@property(readonly, nonatomic) unsigned int hiDPI;
|
||||
@property(readonly, nonatomic) unsigned int displayID;
|
||||
@property(readonly, nonatomic) id terminationHandler;
|
||||
@property(readonly, nonatomic) id queue;
|
||||
@property(readonly, nonatomic) struct CGPoint whitePoint;
|
||||
@property(readonly, nonatomic) struct CGPoint bluePrimary;
|
||||
@property(readonly, nonatomic) struct CGPoint greenPrimary;
|
||||
@property(readonly, nonatomic) struct CGPoint redPrimary;
|
||||
@property(readonly, nonatomic) unsigned int maxPixelsHigh;
|
||||
@property(readonly, nonatomic) unsigned int maxPixelsWide;
|
||||
@property(readonly, nonatomic) struct CGSize sizeInMillimeters;
|
||||
@property(readonly, nonatomic) NSString* name;
|
||||
@property(readonly, nonatomic) unsigned int serialNum;
|
||||
@property(readonly, nonatomic) unsigned int productID;
|
||||
@property(readonly, nonatomic) unsigned int vendorID;
|
||||
- (BOOL)applySettings:(id)arg1;
|
||||
- (void)dealloc;
|
||||
- (id)initWithDescriptor:(id)arg1;
|
||||
|
||||
@end
|
||||
|
||||
@interface CGVirtualDisplayDescriptor : NSObject {
|
||||
unsigned int _vendorID;
|
||||
unsigned int _productID;
|
||||
unsigned int _serialNum;
|
||||
NSString* _name;
|
||||
struct CGSize _sizeInMillimeters;
|
||||
unsigned int _maxPixelsWide;
|
||||
unsigned int _maxPixelsHigh;
|
||||
struct CGPoint _redPrimary;
|
||||
struct CGPoint _greenPrimary;
|
||||
struct CGPoint _bluePrimary;
|
||||
struct CGPoint _whitePoint;
|
||||
id _queue;
|
||||
id _terminationHandler;
|
||||
}
|
||||
|
||||
@property(retain, nonatomic) id queue;
|
||||
@property(retain, nonatomic) NSString* name;
|
||||
@property(nonatomic) struct CGPoint whitePoint;
|
||||
@property(nonatomic) struct CGPoint bluePrimary;
|
||||
@property(nonatomic) struct CGPoint greenPrimary;
|
||||
@property(nonatomic) struct CGPoint redPrimary;
|
||||
@property(nonatomic) unsigned int maxPixelsHigh;
|
||||
@property(nonatomic) unsigned int maxPixelsWide;
|
||||
@property(nonatomic) struct CGSize sizeInMillimeters;
|
||||
@property(nonatomic) unsigned int serialNum;
|
||||
@property(nonatomic) unsigned int productID;
|
||||
@property(nonatomic) unsigned int vendorID;
|
||||
- (void)dealloc;
|
||||
- (id)init;
|
||||
@property(copy, nonatomic) id terminationHandler;
|
||||
|
||||
@end
|
||||
|
||||
@interface CGVirtualDisplayMode : NSObject {
|
||||
unsigned int _width;
|
||||
unsigned int _height;
|
||||
double _refreshRate;
|
||||
}
|
||||
|
||||
@property(readonly, nonatomic) double refreshRate;
|
||||
@property(readonly, nonatomic) unsigned int height;
|
||||
@property(readonly, nonatomic) unsigned int width;
|
||||
- (id)initWithWidth:(unsigned int)arg1
|
||||
height:(unsigned int)arg2
|
||||
refreshRate:(double)arg3;
|
||||
|
||||
@end
|
||||
|
||||
@interface CGVirtualDisplaySettings : NSObject {
|
||||
NSArray* _modes;
|
||||
unsigned int _hiDPI;
|
||||
}
|
||||
|
||||
@property(nonatomic) unsigned int hiDPI;
|
||||
- (void)dealloc;
|
||||
- (id)init;
|
||||
@property(retain, nonatomic) NSArray* modes;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = process.platform === 'darwin'
|
||||
? require('../build/Release/virtual_display.node')
|
||||
: {
|
||||
create: () => { throw new Error('Virtual displays only supported on macOS'); },
|
||||
destroy: () => { throw new Error('Virtual displays only supported on macOS'); },
|
||||
forceCleanup: () => { throw new Error('Virtual displays only supported on macOS'); }
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@electron-ci/virtual-display",
|
||||
"version": "1.0.0",
|
||||
"description": "Virtual display for multi-monitor testing",
|
||||
"main": "./lib/virtual-display.js",
|
||||
"scripts": {
|
||||
"install": "node-gyp configure && node-gyp build",
|
||||
"clean": "rm -rf build",
|
||||
"build-electron": "electron-rebuild"
|
||||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"node-addon-api": "^8.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
#import "VirtualDisplayBridge.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
static NSMutableDictionary<NSNumber*, CGVirtualDisplay*>* sDisplays;
|
||||
static NSInteger sCounter = 0;
|
||||
|
||||
@implementation VirtualDisplayBridge
|
||||
|
||||
+ (void)initialize {
|
||||
if (self == [VirtualDisplayBridge class]) {
|
||||
sDisplays = [NSMutableDictionary new];
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSInteger)create:(int)width height:(int)height x:(int)x y:(int)y {
|
||||
int step = 1;
|
||||
int minX = 720, minY = 720, maxX = 8192, maxY = 8192;
|
||||
int minMultiplier = MAX((int)ceil((double)minX / (width * step)),
|
||||
(int)ceil((double)minY / (height * step)));
|
||||
int maxMultiplier = MIN((int)floor((double)maxX / (width * step)),
|
||||
(int)floor((double)maxY / (height * step)));
|
||||
|
||||
CGVirtualDisplayDescriptor* descriptor = [[CGVirtualDisplayDescriptor alloc] init];
|
||||
if (!descriptor)
|
||||
return 0;
|
||||
|
||||
descriptor.queue =
|
||||
dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0);
|
||||
descriptor.name =
|
||||
[NSString stringWithFormat:@"Dummy %dx%d", width, height];
|
||||
descriptor.whitePoint = CGPointMake(0.950, 1.000);
|
||||
descriptor.redPrimary = CGPointMake(0.454, 0.242);
|
||||
descriptor.greenPrimary = CGPointMake(0.353, 0.674);
|
||||
descriptor.bluePrimary = CGPointMake(0.157, 0.084);
|
||||
descriptor.maxPixelsWide = (unsigned int)(width * step * maxMultiplier);
|
||||
descriptor.maxPixelsHigh = (unsigned int)(height * step * maxMultiplier);
|
||||
|
||||
double diagonal = (24.0 * 25.4) /
|
||||
sqrt((double)(width * width) + (double)(height * height));
|
||||
descriptor.sizeInMillimeters =
|
||||
CGSizeMake((double)width * diagonal, (double)height * diagonal);
|
||||
|
||||
descriptor.serialNum = arc4random();
|
||||
descriptor.productID =
|
||||
(unsigned int)(MIN(width - 1, 255) * 256 + MIN(height - 1, 255));
|
||||
descriptor.vendorID = 0xF0F0;
|
||||
|
||||
CGVirtualDisplay* display =
|
||||
[[CGVirtualDisplay alloc] initWithDescriptor:descriptor];
|
||||
if (!display)
|
||||
return 0;
|
||||
|
||||
NSMutableArray* modes = [NSMutableArray new];
|
||||
for (int mult = minMultiplier; mult <= maxMultiplier; mult++) {
|
||||
unsigned int w = (unsigned int)(width * mult * step);
|
||||
unsigned int h = (unsigned int)(height * mult * step);
|
||||
CGVirtualDisplayMode* mode =
|
||||
[[CGVirtualDisplayMode alloc] initWithWidth:w height:h refreshRate:60.0];
|
||||
if (mode)
|
||||
[modes addObject:mode];
|
||||
}
|
||||
|
||||
CGVirtualDisplaySettings* settings = [[CGVirtualDisplaySettings alloc] init];
|
||||
if (!settings)
|
||||
return 0;
|
||||
|
||||
settings.modes = modes;
|
||||
settings.hiDPI = 0;
|
||||
|
||||
if (![display applySettings:settings])
|
||||
return 0;
|
||||
|
||||
CGDirectDisplayID displayID = [display displayID];
|
||||
if (![self waitForDisplayRegistration:displayID])
|
||||
return 0;
|
||||
|
||||
[self positionDisplay:displayID x:x y:y];
|
||||
|
||||
sCounter++;
|
||||
sDisplays[@(sCounter)] = display;
|
||||
return sCounter;
|
||||
}
|
||||
|
||||
+ (BOOL)destroy:(NSInteger)displayId {
|
||||
NSNumber* key = @(displayId);
|
||||
if (!sDisplays[key])
|
||||
return NO;
|
||||
[sDisplays removeObjectForKey:key];
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (BOOL)forceCleanup {
|
||||
[sDisplays removeAllObjects];
|
||||
sCounter = 0;
|
||||
|
||||
CGDisplayConfigRef config = NULL;
|
||||
if (CGBeginDisplayConfiguration(&config) == kCGErrorSuccess) {
|
||||
CGCompleteDisplayConfiguration(config, kCGConfigurePermanently);
|
||||
}
|
||||
|
||||
usleep(2000000);
|
||||
|
||||
config = NULL;
|
||||
if (CGBeginDisplayConfiguration(&config) == kCGErrorSuccess) {
|
||||
CGCompleteDisplayConfiguration(config, kCGConfigureForSession);
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
#pragma mark - Private
|
||||
|
||||
+ (BOOL)waitForDisplayRegistration:(CGDirectDisplayID)targetID {
|
||||
CGDirectDisplayID displays[32];
|
||||
uint32_t count = 0;
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
if (CGGetActiveDisplayList(32, displays, &count) == kCGErrorSuccess) {
|
||||
for (uint32_t j = 0; j < count; j++) {
|
||||
if (displays[j] == targetID)
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
usleep(100000);
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (void)positionDisplay:(CGDirectDisplayID)displayID x:(int)x y:(int)y {
|
||||
CGDisplayConfigRef config = NULL;
|
||||
CGError err = CGBeginDisplayConfiguration(&config);
|
||||
if (err != kCGErrorSuccess)
|
||||
return;
|
||||
|
||||
err = CGConfigureDisplayOrigin(config, displayID, (int32_t)x, (int32_t)y);
|
||||
if (err != kCGErrorSuccess) {
|
||||
CGCancelDisplayConfiguration(config);
|
||||
return;
|
||||
}
|
||||
|
||||
CGCompleteDisplayConfiguration(config, kCGConfigurePermanently);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,197 @@
|
||||
#include <js_native_api.h>
|
||||
#include <node_api.h>
|
||||
#include "VirtualDisplayBridge.h"
|
||||
|
||||
namespace {
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
int default_val;
|
||||
int* ptr;
|
||||
} PropertySpec;
|
||||
|
||||
// Helper function to get an integer property from an object
|
||||
bool GetIntProperty(napi_env env,
|
||||
napi_value object,
|
||||
const char* prop_name,
|
||||
int* result,
|
||||
int default_value) {
|
||||
*result = default_value;
|
||||
|
||||
bool has_prop;
|
||||
if (napi_has_named_property(env, object, prop_name, &has_prop) != napi_ok ||
|
||||
!has_prop) {
|
||||
return true;
|
||||
}
|
||||
|
||||
napi_value prop_value;
|
||||
if (napi_get_named_property(env, object, prop_name, &prop_value) != napi_ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (napi_get_value_int32(env, prop_value, result) != napi_ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Helper function to validate and parse object properties
|
||||
bool ParseObjectProperties(napi_env env,
|
||||
napi_value object,
|
||||
PropertySpec props[],
|
||||
size_t prop_count) {
|
||||
// Process all properties
|
||||
for (size_t i = 0; i < prop_count; i++) {
|
||||
if (!GetIntProperty(env, object, props[i].name, props[i].ptr,
|
||||
props[i].default_val)) {
|
||||
char error_msg[50];
|
||||
snprintf(error_msg, sizeof(error_msg), "%s must be a number",
|
||||
props[i].name);
|
||||
napi_throw_error(env, NULL, error_msg);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for unknown properties
|
||||
napi_value prop_names;
|
||||
uint32_t count;
|
||||
napi_get_property_names(env, object, &prop_names);
|
||||
napi_get_array_length(env, prop_names, &count);
|
||||
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
napi_value prop_name;
|
||||
napi_get_element(env, prop_names, i, &prop_name);
|
||||
size_t len;
|
||||
char name[20];
|
||||
napi_get_value_string_utf8(env, prop_name, name, sizeof(name), &len);
|
||||
|
||||
bool found = false;
|
||||
for (size_t j = 0; j < prop_count; j++) {
|
||||
if (strcmp(name, props[j].name) == 0) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
napi_throw_error(env, NULL, "Object contains unknown properties");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// virtualDisplay.create()
|
||||
napi_value create(napi_env env, napi_callback_info info) {
|
||||
size_t argc = 1;
|
||||
napi_value args[1];
|
||||
|
||||
if (napi_get_cb_info(env, info, &argc, args, NULL, NULL) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int width = 1920, height = 1080, x = 0, y = 0;
|
||||
|
||||
PropertySpec props[] = {{"width", 1920, &width},
|
||||
{"height", 1080, &height},
|
||||
{"x", 0, &x},
|
||||
{"y", 0, &y}};
|
||||
|
||||
if (argc >= 1) {
|
||||
napi_valuetype valuetype;
|
||||
if (napi_typeof(env, args[0], &valuetype) != napi_ok) {
|
||||
napi_throw_error(env, NULL, "Failed to get argument type");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (valuetype == napi_object) {
|
||||
if (!ParseObjectProperties(env, args[0], props,
|
||||
sizeof(props) / sizeof(props[0]))) {
|
||||
return NULL;
|
||||
}
|
||||
} else {
|
||||
napi_throw_error(env, NULL, "Expected an object as the argument");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
NSInteger displayId = [VirtualDisplayBridge create:width
|
||||
height:height
|
||||
x:x
|
||||
y:y];
|
||||
|
||||
if (displayId == 0) {
|
||||
napi_throw_error(env, NULL, "Failed to create virtual display");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
napi_value result;
|
||||
if (napi_create_int64(env, displayId, &result) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// virtualDisplay.forceCleanup()
|
||||
napi_value forceCleanup(napi_env env, napi_callback_info info) {
|
||||
BOOL result = [VirtualDisplayBridge forceCleanup];
|
||||
|
||||
napi_value js_result;
|
||||
if (napi_get_boolean(env, result, &js_result) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return js_result;
|
||||
}
|
||||
|
||||
// virtualDisplay.destroy()
|
||||
napi_value destroy(napi_env env, napi_callback_info info) {
|
||||
size_t argc = 1;
|
||||
napi_value args[1];
|
||||
|
||||
if (napi_get_cb_info(env, info, &argc, args, NULL, NULL) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (argc < 1) {
|
||||
napi_throw_error(env, NULL, "Expected number argument");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int64_t displayId;
|
||||
if (napi_get_value_int64(env, args[0], &displayId) != napi_ok) {
|
||||
napi_throw_error(env, NULL, "Expected number argument");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
BOOL result = [VirtualDisplayBridge destroy:(NSInteger)displayId];
|
||||
|
||||
napi_value js_result;
|
||||
if (napi_get_boolean(env, result, &js_result) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return js_result;
|
||||
}
|
||||
|
||||
napi_value Init(napi_env env, napi_value exports) {
|
||||
napi_property_descriptor descriptors[] = {
|
||||
{"create", NULL, create, NULL, NULL, NULL, napi_default, NULL},
|
||||
{"destroy", NULL, destroy, NULL, NULL, NULL, napi_default, NULL},
|
||||
{"forceCleanup", NULL, forceCleanup, NULL, NULL, NULL, napi_default,
|
||||
NULL}};
|
||||
|
||||
if (napi_define_properties(env, exports,
|
||||
sizeof(descriptors) / sizeof(*descriptors),
|
||||
descriptors) != napi_ok) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return exports;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
|
||||
@@ -13,6 +13,7 @@
|
||||
"@electron-ci/is-valid-window": "*",
|
||||
"@electron-ci/osr-gpu": "*",
|
||||
"@electron-ci/uv-dlopen": "*",
|
||||
"@electron-ci/virtual-display": "*",
|
||||
"@electron/fuses": "^2.1.2",
|
||||
"@electron/packager": "^18.3.2",
|
||||
"@types/basic-auth": "^1.1.8",
|
||||
|
||||
@@ -467,6 +467,14 @@ __metadata:
|
||||
languageName: unknown
|
||||
linkType: soft
|
||||
|
||||
"@electron-ci/virtual-display@npm:*, @electron-ci/virtual-display@workspace:spec/fixtures/native-addon/virtual-display":
|
||||
version: 0.0.0-use.local
|
||||
resolution: "@electron-ci/virtual-display@workspace:spec/fixtures/native-addon/virtual-display"
|
||||
dependencies:
|
||||
node-addon-api: "npm:^8.3.0"
|
||||
languageName: unknown
|
||||
linkType: soft
|
||||
|
||||
"@electron/asar@npm:^3.2.13":
|
||||
version: 3.2.13
|
||||
resolution: "@electron/asar@npm:3.2.13"
|
||||
@@ -3965,6 +3973,7 @@ __metadata:
|
||||
"@electron-ci/is-valid-window": "npm:*"
|
||||
"@electron-ci/osr-gpu": "npm:*"
|
||||
"@electron-ci/uv-dlopen": "npm:*"
|
||||
"@electron-ci/virtual-display": "npm:*"
|
||||
"@electron/fuses": "npm:^2.1.2"
|
||||
"@electron/packager": "npm:^18.3.2"
|
||||
"@types/basic-auth": "npm:^1.1.8"
|
||||
@@ -7740,6 +7749,15 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"node-addon-api@npm:^8.3.0":
|
||||
version: 8.7.0
|
||||
resolution: "node-addon-api@npm:8.7.0"
|
||||
dependencies:
|
||||
node-gyp: "npm:latest"
|
||||
checksum: 10c0/31a03b00f6b0753ab08360952fdf80a1abb619dcf8125fa1ab07e3a414da050963440c3a86c77a0334c0be7a71acb5e242dc468b79201ee6151c7b943afe946d
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"node-fetch@npm:^2.6.0":
|
||||
version: 2.7.0
|
||||
resolution: "node-fetch@npm:2.7.0"
|
||||
|
||||
Reference in new issue
Block a user